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
  • 121,762
  • 30
  • 236
  • 257
Joshua
  • 73
  • 8
  • 2
    Check out [C Operator Precedence](http://en.cppreference.com/w/c/language/operator_precedence) – Austin Brunkhorst Mar 27 '16 at 01:34
  • @Joshua: What are these "`*x[10]` and `(*x)[10]`" supposed to be? Declarators or expressions? Your question is ambiguous and does not allow for a specific answer until this ambiguity is resolved. – AnT Mar 27 '16 at 01:35
  • ah I forgot to point out that it's declarators. int *x[10] and int (*x)[10]. – Joshua Mar 27 '16 at 01:37
  • 2
    @Austin Brunkhorst: If these are declarators, as OP confirmed, then operators have nothing to do with it. These tokens are not operators. – AnT Mar 27 '16 at 01:38

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
  • 53,843
  • 10
  • 127
  • 237
  • 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