1

Last time we had a test in programming and one of the questions was the difference between initializing

int *x[10];

and

int (*x)[10];

Can anyone clarify this for me?

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
Joshua
  • 83
  • 1
  • 8

1 Answers1

4
Type *x[10];

defines x as an array of 10 pointers to Type. So x itself is an array that contains pointers to Type. On the other hand,

Type (*x)[10];

defines x as a pointer to array-10 of Type. Hence x points to the befinning of an array of size 10, and the array contains objects of type Type. See this for a great introduction to how to read complicated declarations in C, and also try cdecl.org.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • 1
    Thank you. I couldn't find anything that explains the difference thoroughly. This answered my question. – Joshua Mar 27 '16 at 01:35
  • @Joshua You're welcome, glad it helped. – vsoftco Mar 27 '16 at 01:38
  • So in essence Type (*x)[10]; is the same as x[10]; ?? – user2419083 Mar 27 '16 at 01:50
  • 2
    @user2419083 No. When you increment `x` in the first case, it "jumps" over 10 elements, as it points to an array. So think of the array as a contiguous area of storage, of size `10*sizeof(Type)`. In the second case, `x` points to the beginning of the array, and incrementing it results in "jumping" over 1 element. Hope this clarifies it. – vsoftco Mar 27 '16 at 01:51
  • Added bit: `sizeof (int *x[10])` is the size of 10* `int`. `sizeof (int (*x)[10]` is the size of a single pointer. – chux - Reinstate Monica Mar 27 '16 at 02:59
  • 1
    @chux Small typo: `sizeof (int *x[10])` is the size of **`10* sizeof(int*)`** – vsoftco Mar 27 '16 at 03:38