I'm familiar with multidimensional arrays being accessed as such: arr[rows][cols] which makes sense to me when I imagine it as a grid or coordinate system and locating points. But I'm confused about the line below. I understand it is picking up a pointer to some struct located in the array of structures I just have a hard time imagining which location this could represent in terms of the coordinate system I'm used to...its a bitmap by the way and SOMETHING is a pixel.
//what does this line mean SOMETHING *o = original + row*cols + col;
for (row=0; row < rows; row++)
for (col=0; col < cols; col++) {
SOMETHING* o = original + row*cols + col;
SOMETHING* n = (*new) + row*cols + (cols-1-col);
*n = *o;
}
Think about how arrays are laid out in memory. A multidimensional array is just an array of arrays, so say you had an array like SOMETHING[10][10]
.
The memory layout would be:
[0][0], [0][1], .. [0][9], [1][0], [1][1].. [9][9]
This actually is exactly the same as allocating sizeof(SOMETHING)*100
.
What the line SOMETHING* o = original + row*cols + col;
is saying is "make a pointer to object of type SOMETHING
".
The pointer address should be:
the memory address of original,
add row times cols to it,
which will place it at the start of a row,
to get to the exact position of an object in the array
A two dimensional array such as:
{{00,01,02,03},
{10,11,12,13},
{20,21,22,23},
{30,31,32,33}}
Will be placed in memory in order. Just like this:
{00,01,02,03,10,11,12,13,20,21,22,23,30,31,32,33}
So, when you access the array with a[i][j]
, you can also access the array with
a + i *(ELEMENTS_IN_ROW) + j
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With