What is the difference between the following declarations:
int* arr1[8];
int (*arr2)[8];
int *(arr3[8]);
What is the general rule for under
Use the cdecl program, as suggested by K&R.
$ cdecl
Type `help' or `?' for help
cdecl> explain int* arr1[8];
declare arr1 as array 8 of pointer to int
cdecl> explain int (*arr2)[8]
declare arr2 as pointer to array 8 of int
cdecl> explain int *(arr3[8])
declare arr3 as array 8 of pointer to int
cdecl>
It works the other way too.
cdecl> declare x as pointer to function(void) returning pointer to float
float *(*x)(void )
int* arr[8]; // An array of int pointers.
int (*arr)[8]; // A pointer to an array of integers
The third one is same as the first.
The general rule is operator precedence. It can get even much more complex as function pointers come into the picture.
As a rule of thumb, right unary operators (like []
, ()
, etc) take preference over left ones. So, int *(*ptr)()[];
would be a pointer that points to a function that returns an array of pointers to int (get the right operators as soon as you can as you get out of the parenthesis)
Here's how I interpret it:
int *something[n];
Note on precedence: array subscript operator (
[]
) has higher priority than dereference operator (*
).
So, here we will apply the []
before *
, making the statement equivalent to:
int *(something[i]);
Note on how a declaration makes sense:
int num
meansnum
is anint
,int *ptr
orint (*ptr)
means, (value atptr
) is anint
, which makesptr
a pointer toint
.
This can be read as, (value of the (value at ith index of the something)) is an integer. So, (value at the ith index of something) is an (integer pointer), which makes the something an array of integer pointers.
In the second one,
int (*something)[n];
To make sense out of this statement, you must be familiar with this fact:
Note on pointer representation of array:
somethingElse[i]
is equivalent to*(somethingElse + i)
So, replacing somethingElse
with (*something)
, we get *(*something + i)
, which is an integer as per declaration. So, (*something)
given us an array, which makes something equivalent to (pointer to an array).
I think we can use the simple rule ..
example int * (*ptr)()[];
start from ptr
" ptr
is a pointer to "
go towards right ..its ")" now go left its a "("
come out go right "()" so
" to a function which takes no arguments " go left "and returns a pointer " go right "to
an array" go left " of integers "
Here's an interesting website that explains how to read complex types in C: http://www.unixwiz.net/techtips/reading-cdecl.html