starter
starter

Reputation: 325

convert multidimensional array to single dimensional in C

If I had an array defined as follows in C:

int B[d1][d2][d3][d4][d5][d6][d7][d8][d9];

Then it is easy to convert "B" into single dimensional one. But what if I have an array in C, which is defined as follows:

int********* A;
//which will be allocated as follows for example
A = (int*********) malloc(N*sizeof(int********));
for(int i=0; i<N; i++)
{
 //differentSizes will be distinct for every "i"
 //the same distinctness of sizes will be for every other 
 //inner parts of all inner for loops
 compute(&differentSizes);
 A[i] = (int********) malloc(differentSizes*sizeof(int*******));
 for(...)
 {
  ...
 }
}

Where "A" will have very large sizes for every dimension and they will all be distinct for all the innerarrays/subarrays of "A".

My question: Is there an efficient way to convert "A" into a single dimensional one? If possible can you show a simple example? Thanks!

Upvotes: 1

Views: 4437

Answers (2)

ThePosey
ThePosey

Reputation: 2734

The way your array is declared all the contents will be contiguous in memory. If you could determine the number of elements you could just copy the array over to a single dimensional one or iterate over the original it depends on what you want to do:

int* singleIndex = (int*)B;

for (int i = 0; i < d1 * d2...dN; i++)
{
    printf("Element # %d = %d\n", i, *singleIndex);
}

for instance.

Now if you were doing heap initialization of the array then this wouldn't work since all the memory would be scattered around on the heap but for static/stack allocated arrays it would.

Upvotes: 1

user529758
user529758

Reputation:

I don't see your problem. Multidimensional arrays are contigous in memory, so a type conversion will work:

int B[13][37];
int *oneDimension = (int *)B;

From now on, you can access the elements of B by computing the appropriate offset from its size in each dimension; using the example above:

int valueAtB_2_6 = oneDimension[2 * 13 + 6];

Upvotes: 3

Related Questions