Pointers to Multidimensional Arrays
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:
Array indices act as both pointer addition and indirection.
Harry.
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:
|
Array indices act as both pointer addition and indirection.
Harry.
Harry.
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
![](wink.gif)
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
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement