Reputation: 894
I'm new to c++ and trying to understand how memory allocating is done for 2D arrays.I have gone through several threads in SOF and these answers.
Those answers says that continuous memory allocation happen for 2D arrays as well like for normal arrays. (correct me if I'm wrong) Answer 2 mention that it should be able to access array[i][j]
th element using*(array + (i * ROW_SIZE) + j)
But when I'm trying to do that it gives me an unexpected result.
Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int array[2][2] = { {1, 2}, {3, 4} };
cout<<*((array+1*2) + 1)<<endl;
cout<<**((array+1*2) + 1)<<endl;
return 0;
}
Result:
0x76e1f4799008
2012576581
It doesn't give me array[i][j]
th element. Can some one explain what is happening here, whether that solution is wrong or have i misunderstood the previous answers.
Upvotes: 2
Views: 231
Reputation: 1472
First you have to get a pointer to the first element of the whole thing, i.e. not just to the first row:
int *p = &array[0][0]
After that, you can index p
like you want:
std::cout << *(p + 1*2 + 1) << std::endl;
The reason why your initial tries didn't work is related to types. What is happening is that in your first try you are trying to evaluate
*(array + 1*2 + 1)
Now since, array
is of type "array-of-length-2" containing "array-of-length-2" containing int
s, i.e. (int[2])[2]
what this will do is increment array
with 3 times the size of its elements, which in turn are int[2]
. This will jump outside of your array. In fact *(array+3)
is equivalent to array[3]
. Now, that clearly is something with type int[2]
, which will decay to a pointer when you try to print it. In your second try, you dereference this, yielding something like array[3][0]
, which now is of the right type, but again, points outside of the array.
Upvotes: 3
Reputation: 60
array is 2D pointer
**array = array[0][0]
*(*array + j) = array[0][j]
*(*(array+i) + j) = array[i][j]
Upvotes: 1
Reputation: 768
it is more like when you simulate a 2d array as a one dimensional array like this
0 1 2
3 4 5
6 7 8
and the array will be 0 1 2 3 4 5 6 7 8 to access 4 it should be *(a[0]+(1*3)+1)a[0] is the same as a(name of array).
Upvotes: 3