If I write
int *columns[32];
am I defining an array with 32 pointers to int
s?
Or is it a pointer to an array of 32 int
s?
How do I differentiate between the two? Is there a difference?
UPDATE: You can notice that pointer to integer incremented by 4 bytes (size of 32 bit integer) whereas pointer to array of integer incremented by 20 bytes (size of int arr [5] i.e. size of 5 int of 32 bit each). This demonstrates the difference. Show activity on this post.
The difference is that int* points to an int type, but int (*x) [6] points to an array of 6 ints. Actually in your example, is undefined** behavior, you know these are of two different types, but in C you do what you want. I'll just use a pointer to an array of six ints. Would be printed.
Declaration of the pointer to an array: // pointer to an array of five numbers int (* ptr) [5] = NULL; The above declaration is the pointer to an array of five integers. We use parenthesis to pronounce pointer to an array.
On dereferencing a pointer expression we get a value pointed to by that pointer expression. Pointer to an array points to an array, so on dereferencing it, we should get the array, and the name of array denotes the base address. So whenever a pointer to an array is dereferenced, we get the base address of the array to which it points.
Expanding on a comment to another answer:
There's a fairly straightforward procedure for reading C declarations. Start with the leftmost identifier in the declarator and work your way out, remembering that []
and ()
bind before *
. Given the declaration
int *columns[32];
break it down as
columns -- columns
columns[32] -- is a 32-element array
*columns[32] -- of pointers
int *columns[32] -- to int.
If the declaration had been
int (*columns)[32];
then it would break down as
columns -- columns
(*columns) -- is a pointer
(*columns)[32] -- to a 32-element array
int (*columns)[32] -- of int.
This will also help you build up complex declarations. Suppose you wanted to declare an array of pointers to functions returning pointers to arrays of char:
f -- f
f[N] -- is an N-element array
*f[N] -- of pointers
(*f[N])() -- to functions
*(*f[N])() -- returning pointers
(*(*f[N])())[M] -- to M-element arrays
*(*(*f[N])())[M] -- of pointers
char *(*(*f[N])())[M]; -- to char
cdecl is a nice tool, but after you'd done this exercise a few times, you shouldn't need it.
When in doubt - ask cdecl
$> cdecl
Type `help' or `?' for help
cdecl> explain int *columns[32]
declare columns as array 32 of pointer to int
EDIT In response to comments: I found cdecl source on Google Code Search. It requires GNU readline library. I think it shouldn't be a problem to compile it on Mac OS X or Windows.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With