Accessing multidiemsional arrays passed in as pointers

Started by
12 comments, last by LifeOfTamir 19 years, 10 months ago
i believe you should be passing the array as an int * not as an int **. X-D arrays are really just 1D arrays stored in memory in the serial format: row1, row2, row3, etc... so by passing the array variable you get all the information you need (i.e. the head of the array).

you are making the assumption in your code that the array is actually stored 2 dimensionally in memory. it isn't. like i said, it's just a 1D block of memory: row1, row2, etc... go with the code that you got in your first reply.


this should work, but you might have to debug it.
int foo[10][10];yourFunction( foo, 10, 10 );yourFunction ( int *theArray, int width, int height ){    for (int x = 0; x < width; ++x )    {        for (int y = 0; y < height; ++y )        {             int thisElement = theArray[width * y + x];        }    }}


-me

[edited by - Palidine on June 8, 2004 12:52:56 PM]
Advertisement
Brilliant! thanks alot guys!

okay the problem is solved but just so i know whats going on:

if 2D arrays are stored in serial format as Palidine said then does the end of row1 contain a pointer to the beginning of row2? No, the first array is an array of pointers pointing to arrays? I think i get wants going on but i can''t picture it...or write in words....maybe i don''t know whats going on *thinks*...
"Without the 0, alot of big numbers would just sit around looking rather stupid"
no, there are no pointers anywhere in the memory space. it''s just a straight up block of memory. because the compiler knows that you declared the array as int foo[10][10], it''s basically doing that same math to access the [x][y] spot in the array. what this means is that you cannot create multi-dimensional arrays with new/malloc and access them with [][] operators. any multi-dimensional array you want to have on the heap will have to be accessed by the [width * y + x] method. if it''s 3-D, 4-D, etc, you can work out the math for accessing the array.

multi-dimensional arrays, are, for all intents and purposes a compiler trick.

-me
quote:
what this means is that you cannot create multi-dimensional arrays with new/malloc and access them with [][] operators


You can create multidimensional arrays with new, and you can access them using [][] syntax.

int (*pint)[10] = new int[100][10];pint[9][9] = 100;


[edited by - Jingo on June 8, 2004 2:09:04 PM]

This topic is closed to new replies.

Advertisement