Reputation: 836
I'm learning C and have a question of: Explain the difference between int (*twod)[3] as a parameter as compared to int *(twod[3]).
I don't really know what the difference is completely. If someone could help me to understand the difference that would be much appreciated.
Upvotes: 0
Views: 60
Reputation: 8058
Remember these rules for C declares
And precedence never will be in doubt
Start with the suffix, proceed with the prefix
And read both sets from the inside, out.
Except as modified by parentheses, of course,
int (*twod)[3]
is a (parenthesized (prefix) pointer to) (suffix) 3-element array of (prefix) int.
`int *(twod[3])' is a (parenthesized (suffix) 3-element array of) (prefix) pointer to (prefix) int.
int *twod[3]
is likewise a (suffix) 3-element array of (prefix) pointer to (prefix) int.
There are tools out there which will apply these rules and do exactly the conversion I've just described, if you need assistance understanding more complicated declarations. (I wrote one several decades ago known as the C Explainer, or "cex" for short.) But it's worth assigning yourself a bit of homework and practicing doing this manually, because the same precedence rules apply for the addressing operators when you actually use them in your code.
(Though if you're doing anything really complicated, the better answer is to break it up into subexpressions, or into typedefs, so you're only operating on one or two layers at a time.)
Upvotes: 1
Reputation: 1073
One is a pointer to an array, and the other an array of pointers.
In particular, int (*twod)[3]
has three elements, whereas int *(twod[3])
does not yet point to any particular place in memory.
Upvotes: 1