convert multidimensional array to single dimensional in C

拈花ヽ惹草 提交于 2019-12-24 23:16:12

问题


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!


回答1:


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];



回答2:


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.



来源:https://stackoverflow.com/questions/12938357/convert-multidimensional-array-to-single-dimensional-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!