5

Possible Duplicate:
C pointer to array/array of pointers disambiguation

In C, is int *thing[5] an array of five pointers, each pointing to an integer, or a pointer to an array of five integers?

Community
  • 1
  • 1
me_and
  • 15,158
  • 7
  • 59
  • 96

4 Answers4

7

[] trumps * per the C precedence table which means you have an array of five int pointers.

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
Amardeep AC9MF
  • 18,464
  • 5
  • 40
  • 50
6

If in doubt use parenthesis - the maintenance programmers will thank you (as will you at 5am when you finally find the bug!)

Martin Beckett
  • 94,801
  • 28
  • 188
  • 263
4

Maybe is a duplicate... It is an array of five pointers to integer; the program cdecl cited in a similar question can be useful for newbie:

cdecl> explain int *t[5];
declare t as array 5 of pointer to int
ShinTakezou
  • 9,432
  • 1
  • 29
  • 39
  • Also: `cdecl> explain int (* thing)[5] --> declare thing as pointer to array 5 of int` This gives the pointer to an array of 5 ints he asked about. – Tim Schaeffer Jun 24 '10 at 16:19
0

Absent any explicit grouping with parentheses, both the array subscript operator [] and function call operator () bind before *, so

T *a[N];        -- a is an N-element array of pointer to T
T (*a)[N];      -- a is a pointer to an N-element array of T

T *f();         -- f is a function returning pointer to T
T (*f)();       -- f is a pointer to a function returning T

This follows from the grammar (taken from Harbison & Steele, 5th ed., appendix B):

declarator:
  pointer-declarator
  direct-declarator

pointer-declarator:
  pointer direct-declarator

pointer:
  * type-qualifier-listopt
  * type-qualifier-listopt pointer

direct-declarator:
  simple-declarator
  ( declarator )
  function-declarator
  array-declarator

function-declarator:
  direct-declarator ( parameter-type-list )
  direct-declarator ( identifier-listopt )

array-declarator:
  direct-declarator [ constant-expressionopt ]
  direct-declarator [ array-qualifier-listopt array-size-expressionopt ] 
  direct-declarator [ array-qualifier-listopt * ]
John Bode
  • 119,563
  • 19
  • 122
  • 198