What is the following code doing?
int g[] = {9,8}; int (*j) = g;
From my understanding its creating a pointer to an array of 2 ints. But then why does this work:
int x = j[0];
and this not work:
int x = (*j)[0];
Pointers to an array points the address of memory block of an array variable. The following is the syntax of array pointers. datatype *variable_name[size]; Here, datatype − The datatype of variable like int, char, float etc.
Can we create an array of pointers in C? Yes, we can.
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.
An array is a pointer, and you can store that pointer into any pointer variable of the correct type. For example, int A[10]; int* p = A; p[0] = 0; makes variable p point to the first member of array A.
The parenthesis are superfluous in your example. The pointer doesn't care whether there's an array involved - it only knows that its pointing to an int
int g[] = {9,8}; int (*j) = g;
could also be rewritten as
int g[] = {9,8}; int *j = g;
which could also be rewritten as
int g[] = {9,8}; int *j = &g[0];
a pointer-to-an-array would look like
int g[] = {9,8}; int (*j)[2] = &g; //Dereference 'j' and access array element zero int n = (*j)[0];
There's a good read on pointer declarations (and how to grok them) at this link here: http://www.codeproject.com/Articles/7042/How-to-interpret-complex-C-C-declarations
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