Topics / Pointers & Memory / Q6
What does int (*p)[10] mean versus int *p[10]?
Short answer: int *p[10] is an array of 10 pointers to int, because [] binds more tightly than *. int (*p)[10] is a single pointer to an array of 10 ints; the parentheses make p a pointer first. Incrementing it moves by the size of the whole array (40 bytes with 4-byte ints).
int *a[10]; /* 10 pointers: sizeof a == 10 * sizeof(int *) */
int (*b)[10]; /* 1 pointer: sizeof b == sizeof(void *) */
int m[3][10];
b = m; /* m decays to &m[0], type int (*)[10] */
b + 1; /* address of m[1]: 40 bytes further */
(*b)[2] = 7; /* m[0][2] = 7 */
b[1][2] = 8; /* m[1][2] = 8 */
How to read any C declaration (the "spiral" or "right-left" rule): start at the name, read right (arrays [], functions ()) until a closing parenthesis, then left (*, qualifiers), and repeat outward.
| Declaration | Meaning |
|---|---|
int *p[10] |
p is an array of 10 pointers to int |
int (*p)[10] |
p is a pointer to an array of 10 ints |
int *f(int) |
f is a function taking int, returning pointer to int |
int (*f)(int) |
f is a pointer to a function taking int, returning int |
int (*f[4])(int) |
f is an array of 4 pointers to functions taking int, returning int |
void (*signal(int, void (*)(int)))(int) |
signal is a function taking (int, pointer to function) and returning a pointer to a function taking int |
Use typedefs for anything beyond two levels:
typedef void (*handler_t)(int);
handler_t signal(int sig, handler_t h); /* much clearer than the line above */
typedef int row_t[10];
row_t *b; /* same as int (*b)[10] */
Where pointer-to-array appears: passing 2-D arrays to functions (void f(int m[][10], size_t rows) is int (*m)[10]), and walking a buffer of fixed-size records.