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!
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];
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.