Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexing multidimensional arrays in C

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;
}
like image 976
user2499298 Avatar asked Dec 26 '22 12:12

user2499298


2 Answers

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,

  • then add the specific column to it

to get to the exact position of an object in the array

like image 88
HighlyUnavailable Avatar answered Dec 28 '22 05:12

HighlyUnavailable


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

like image 38
Luke Avatar answered Dec 28 '22 05:12

Luke