-1

int val = 7;

int *ptr = &val;

val is a variable of type int and ptr is a pointer to type int so the assignment above is right and there is no warning from compiler.

int val[5] = {5, 3, 2, 33,557};
int (*ptr)[1]=&val;

val is an array of integers and ptr is a pointer to an array of int when run compiler give me a warning:

warning: initialization from incompatible pointer type [enabled by default]

please someone explain me what is the differece between them?

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
Lundu Harianja
  • 443
  • 1
  • 9
  • 17

1 Answers1

2

The warning is because the type of the pointer (pointer to length 1 array of int) doesn't match the type of the array, with is length 5 array of int. You need

int (*ptr)[5]=&val;

There is no warning in the first example because the type of the pointer on the LHS of the initialization matches the type of the pointer on the RHS.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • I'm thinking that 'int (*ptr)[5]=&val;' is not correct as it (almost) say declare an array of 5 pointers to int, then set the (difficult to say exactly which entry in the 'ptr[]' array) is being set to the address of 'val' Perhaps you meant: 'int *ptr[5]; ptr[0] = &val;' – user3629249 Aug 26 '15 at 20:10
  • 2
    @user3629249 No, I meant what I wrote. `int (*ptr)[5]` is an pointer to an array of 5 ints. – juanchopanza Aug 26 '15 at 20:12
  • @user3629249 Here's [a related question](http://stackoverflow.com/questions/859634/c-pointer-to-array-array-of-pointers-disambiguation). – juanchopanza Aug 26 '15 at 20:23
  • @user3629249: The code above is equivalent to `int (*ptr)[5]; ptr = &val;`. `ptr` is a pointer to a 5-element array of `int`, `int *ptr[5]` declares an 5-element array of pointers to `int`, which is an entirely different thing, and not what we want here. – John Bode Aug 26 '15 at 20:31
  • @user3629249 it's cute how you question a 145k user's answer to a trivial question. Hubris is bad! – The Paramagnetic Croissant Aug 26 '15 at 20:37