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?
If I write
am I defining an array with 32 pointers to How do I differentiate between the two? Is there a difference? |
|||
|
When in doubt - ask
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. |
|||||||||||||||||||||
|
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
break it down as
If the declaration had been
then it would break down as
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:
cdecl is a nice tool, but after you'd done this exercise a few times, you shouldn't need it. |
|||||||||
|
You are defining an array of 32 pointers. To define a pointer to an array of 32 ints you have to do
The former declaration instantiates an array with space for 32 * sizeof(int). On the other hand, the latter instantiates a single uninitialized pointer which you can then use as follows:
I hope I made the difference a little bit clear. |
|||||
|
It is an array of 32 pointers to The C grammar rules specify that array access ( The declaration Had the declaration been |
|||||||||||||||||||||
|
A test program is illustrative, especially to those of us who aren't language lawyers:
It appears to be an array of pointers. |
|||||||||||||||||||||
|
Here are some fun declarations for you:
For more fun with multidimensional arrays look at these posts: |
|||
|
Take a look at the links below. They explain how to read C Declarations with easy rules. They may come in handy in the future. |
|||
|
One trick is to read from right to left. Given int* cols[32];
All that left of array is the type of the elements in the array. So we read it as array of pointers to int (and of count 32). |
|||
|
Refer to Question #5 of A 'C' Test: The 0x10 Best Questions for Would-be Embedded Programmers by Nigel Jones* a) int a; // An integer b) int *a; // A pointer to an integer c) int **a; // A pointer to a pointer to an integer d) int a[10]; // An array of 10 integers e) int *a[10]; // An array of 10 pointers to integers f) int (*a)[10]; // A pointer to an array of 10 integers g) int (*a)(int); // A pointer to a function a that takes an integer argument and returns an integer h) int (*a[10])(int); // An array of 10 pointers to functions that take an integer argument and return an integer *Alas, the original article on embedded.com can no longer be found on their website. |
|||
|