Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer to array c++

Tags:

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]; 
like image 839
Sam Adamsh Avatar asked Apr 20 '12 20:04

Sam Adamsh


People also ask

What is pointer to an array in C?

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 Make pointer array in C?

Can we create an array of pointers in C? Yes, we can.

Can pointers point to array?

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.

Can you use a pointer as an array name?

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.


1 Answers

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

like image 140
Ben Cottrell Avatar answered Oct 29 '22 21:10

Ben Cottrell