Advertisement

Pointers to Multidimensional Arrays

Started by April 01, 2001 05:30 PM
2 comments, last by Owie 23 years, 10 months ago
How do you access the values of your array when you access it through a pointer?? Ill explain: struct MyStruct { int X, Y; } *PtrStruct; int main( void ) { PtrStruct = new MyStruct[2][2]; //which is the right way to access it? PtrStruct[0][1]->X = 2 //or PtrStruct->[0][1].X = 2 } How does the pointer work when it has indices? Where do you need the indirection?
It doesn''t quite work like that...

Arrays are basically pointers to allocated areas of memory. So these are exatly equivalent:

x = array[y];

x = *(array + y);

Remember that an array name on its own is a pointer to the first element in the array.


Multidimensional arrays are not quite as simple as one-dimensional arrays. A two-dimensional array is an array of arrays. The space allocated is still sequential in memory, but it is split up into subsections, one for each array. So these are equivalent:

x = array[y][z];

x = *(array + y + z*sizeof(array[0]));


Anyway, getting back to your example, you would actually have to allocate memory for an array of pointers, and for each element of the array, dynamically allocate memory for each sub-array. Like this:

  struct MyStruct{int X, Y;} **PtrStruct;   // note it''s pointer to pointer to MyStructint main( void ){PtrStruct = new (MyStruct *)[2];  // allocate the top-level arrayfor(int i=0; i<2; i++)    PtrStruct[i] = new MyStruct[2];// right way to access it is:PtrStruct[0][1].X = 2;}  


Array indices act as both pointer addition and indirection.

Harry.
Harry.
Advertisement
HarryW is exactly correct! (exactly correct is more correct than just correct )

I asked my prof the exact same question pretty much, and I got the same answer that HarryW said.

"You won''t get wise with the sleep still in your eyes." - Neil Peart
"You won't get wise with the sleep still in your eyes." - Neil Peart
Thanx guys

This topic is closed to new replies.

Advertisement