2

For 1D array, I can use array name as a pointer and add offset to it to access each element of the array. Is there something similar for 2D arrays?

I defined a 2D array as follows

int arr[2][3] = {{1,2,3}, {4,5,6}};

int** arrPtr = arr;

but I got compiler error for the second line. Shouldn't 2D array have type int**?

I came across another thread here:

C++ Accessing Values at pointer of 2D Array

and saw this:

2dArray = new int*[size];

Could someone please tell me what int*[size] means? (size is an int, I presume).

Thanks a lot.

3
  • 1
    while an array can decay to a pointer, array of array cannot decay to double pointer. Prefer using std::array and std::vector over C array Commented Jun 8, 2013 at 14:16
  • 1
    2d array and pointer to pointer have totally different memory layout. 2d array allocate continuous memory while pointer to pointer can point to noncontinuous memory, so they are not exchangable Commented Jun 8, 2013 at 14:18
  • Thanks, it's just sometimes I have to use arrays due to constraints.. Commented Jun 8, 2013 at 14:44

2 Answers 2

3

A multidimensional array defined as yours is is only a single pointer, because the data is encoded in sequence. Therefore, you can do the following:

int arr[2][3]={{1,2,3},{4,5,6}};
int* arrPtr = (int*)arr;

In general, the pointer to the element at arr[a][b] can be accessed by arrPtr + a*bSize + b where bSize is the size of the first array dimension (in this case three).

Your second question relates to dynamic memory allocation - allocating memory at runtime, instead of defining a fixed amount when the program starts. I recommend reviewing dynamic memory allocation on cplusplus.com before working with dynamically allocated 2D arrays.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I just realized the syntax of int*[size] isn't an int multiplied by [size], but an array of pointers..
1

int* array[10] means an array of 10 pointers to integer.

You can access a 2D array with a simple pointer to its first entry and do some maths exploiting the spacial location principle.

int array[2][2] = {{1,2}, {3, 4}};
int* p = &array[0][0];
for(int i=0; i<2*2; i++)
   printf("%d ", *(p++));

If you have a matrix:

 1 2
 3 4

in memory it is encoded as 1 2 3 4 sequentially ;)

1 Comment

@user2465355: here on SO the best thanks is to accept one's answer clicking on the tick here above :P but I'm glad to have been useful

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.