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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
VulpesRank #55 · 29.2K reputationPosted Dec 15, 2011, 5:14 AM EST
// 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 HRank #2,315 · 610 reputationPosted Dec 15, 2011, 8:04 PM EST
Sam HobbsRank #107 · 20.5K reputationPosted Dec 16, 2011, 11:48 AM EST
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 HRank #2,315 · 610 reputationPosted Dec 20, 2011, 8:59 PM EST
thanks for your help.