-1

I was trying a code with pointer arithmetic, but it seems to give error.

The pointer *p to arr gives desired output with pointer arithmetic, but when i do the same with *k, it gives an error.

#include<stdio.h>

main(){
    int arr[]={1,2,3,4};
    int *p=arr;
    int *k={1,2,3,4};
    printf("%d",*arr+2);
    printf("%d",*k+2);
}

I expect that *k+2 gives exact same output as *arr+2, but it doesn't happen that way. What's the possible reason

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Rusher
  • 1
  • 2
  • 2
    Build with warnings enabled and read about the [comma operator](https://en.cppreference.com/w/c/language/operator_other#Comma_operator), because `int *k={1,2,3,4};` doesn't do what you think it does. – Some programmer dude Jul 19 '19 at 08:07

2 Answers2

4

Pointers are not arrays and you can not use the same syntax to initialize them, in the first case p points to the address of the first element of the array while in the second one you are assigning 1 (the first value of the list) as a value to the pointer, in consequence k points to the address 0x01 and since you are not allowed to dereference this address you get an error (probably a segmentation fault).

demo.c:7:5: warning: initialization makes pointer from integer without a cast
     int *k={1,2,3,4};
     ^

But since C99 we can use compound literals, compound literals allows us to create unnamed objects with given list of initialized values, in other words: you can use a cast to an array as initializer.

In this way:

int *k= (int []){1,2,3,4};
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
1

Doing int *k={1,2,3,4}; you are basically declaring a pointer to an int and then initialising it like an array, the syntax is not correct.

Math Lover
  • 148
  • 10