Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Treating one dimensional array as two dimensional at run time

Tags:

arrays

c

I have some data stored in a one dimensional array of size say 'M'. Now I need to treat it as a two dimensional array with dimension NxP, where the product of N and P is equal to M. I know the values of N and P only at runtime. How can I implement such a function in C?

int array[M]; /* one dimensional array where some data is stored*/
int** newArray; /* the dimension of newArray should be NxP such that we can access the data in 'array' as a two-dimensional array*/
like image 275
user4661268 Avatar asked Feb 24 '26 03:02

user4661268


2 Answers

Just cast it to the appropriate array pointer type:

int (*newArray)[N] = (int (*)[N])array;

After that, you can access the array with:

for(int y = 0; y < P; y++) {
    for(int x = 0; x < N; x++) {
        array[y][x] = 42;
    }
}

This is equivalent to the following indexing:

for(int y = 0; y < P; y++) {
    for(int x = 0; x < N; x++) {
        newArray[y*N + x] = 42;
    }
}

This works even if N is only known at run time since C99. Note that you do not need to set up an index array that way, as you would have to do if you used an int**.

like image 122
cmaster - reinstate monica Avatar answered Feb 25 '26 18:02

cmaster - reinstate monica


You don't need to define a new array. You can use the existing one.

Assuming you know N and P, and N is the number of rows, you can access item (i,j) as:

array[i*N + j]
like image 38
dbush Avatar answered Feb 25 '26 20:02

dbush