How is a 2D array stored in memory?
I thought of the following approach where strings are stored as solid blocks of memory.
| _________ || _________ | ________ | ________ | ... | _________ |
Elements are attached as (i, j) β n * i + j, where n is the dimension of the matrix (if it is equal to nxn).
But what if I want to add a new column to it? I have to update every (n + 1) th element in each row, and also shift them to the right, but this is too expensive a calculation.
Another option is to copy the matrix to a new location and update the rows with the new column elements on the fly. But this is not too efficient if the array is large.
And finally, the third option that I thought was to allocate a fixed amount of memory for each row, and when I add a new column, I do not need to translate the rows to the right.
I cannot have spaces in memory, so all blocks must be contiguous.
I do not ask for the implementation of C using pointers and real RAM memory, I'm just interested in learning about a theoretical approach to storing a dynamic 2d array in memory, since it is easy to add new rows or columns to it.
Are there other more effective approaches?
source share