How to understand the application of multi-dimensional array pointer in c plus plus.
thanks in advance.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Dec 15, 2011, 10:14 AM
// create and initialize a 2 x 2 array of ints
int array2d[2][2];
array2d[0][0] = 1;
array2d[0][1] = 2;
array2d[1][0] = 3;
array2d[1][1] = 4;
// traverse using pointer
int *p = (int *)array2d;
for(int i = 0; i < 4; i++) printf("%d\n", *(p + i)); // 1 2 3 4
// access element [1][1] using pointer
int e = *(p + 2 * 1 + 1);
printf("%d\n", e); // 4
return 0;
Traversing the array using a pointer works because the rows of the multidimensional array are stored one after the other in memory.
In general you can access the [i][j]th element of the array by adding:
(row length) * i + j to a pointer to the first element, and then dereferencing the resulting pointer.
Ken HPosted Dec 21, 2011, 1:59 AM
thanks for your help.
Sam HobbsPosted Dec 16, 2011, 4:48 PM
A better solution is to use C++ vectors but the C++ standard did not have specific support for multi-dimensional vectors. There are many articles in other sites and forum answers in other forums showing how to do that. I know I asked about this in the MSDN forums.
I don't know about the new C++ language standard but I sure hope that it has better support for multidimensional arrays, although tecnically they are probably multidimensional vectors.
If you must do it the C way, then see Ted Jensen's Tutorial on Pointers and Arrays in C.
Ken HPosted Dec 16, 2011, 1:04 AM