Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A pointer to 2d array

I have a question about a pointer to 2d array. If an array is something like

int a[2][3]; 

then, is this a pointer to array a?

int (*p)[3] = a; 

If this is correct, I am wondering what does [3] mean from int(*p)[3]?

like image 760
user1047092 Avatar asked Dec 23 '11 15:12

user1047092


People also ask

Can a pointer point to a 2D array?

Pointers and two dimensional Arrays: In a two dimensional array, we can access each element by using two subscripts, where first subscript represents the row number and second subscript represents the column number. The elements of 2-D array can be accessed with the help of pointer notation also.

How do you assign a pointer to a 2D array?

Get the element => *( (int *)aiData + offset ); calculate offset => offset = (1 * coloumb_number)+ 2); Add offset in array base address => (int *)aiData + offset; //here typecast with int pointer because aiData is an array of integer Get the element => *( (int *)aiData + offset );

What is pointer to an array?

When we allocate memory to a variable, pointer points to the address of the variable. Unary operator ( * ) is used to declare a variable and it returns the address of the allocated memory. Pointers to an array points the address of memory block of an array variable.

Can I use a pointer as an array?

So the upshot of that is yes, you can use the [] subscript operator on a pointer expression as well as an array expression. Pointers don't have to be represented as integers - on some older segmented architectures, they were represented as a pair of values (page number and offset).


1 Answers

int a[2][3]; 

a is read as an array 2 of array 3 of int which is simply an array of arrays. When you write,

int (*p)[3] = a;

It declares p as a pointer to the first element which is an array. So, p points to the array of 3 ints which is a element of array of arrays.

Consider this example:

        int a[2][3] +----+----+----+----+----+----+ |    |    |    |    |    |    | +----+----+----+----+----+----+ \_____________/        |        |            |        p    int (*p)[3] 

Here, p is your pointer which points to the array of 3 ints which is an element of array of arrays.

like image 134
cpx Avatar answered Sep 20 '22 18:09

cpx