简体   繁体   English

在C中将多维数组转换为单维

[英]convert multidimensional array to single dimensional in C

If I had an array defined as follows in C: 如果我在C中定义了如下数组:

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

Then it is easy to convert "B" into single dimensional one. 然后,很容易将“ B”转换为一维。 But what if I have an array in C, which is defined as follows: 但是如果我在C中有一个数组,该数组的定义如下:

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". 其中“ A”的每个维度的尺寸都非常大,并且对于“ A”的所有内部阵列/子阵列而言,它们都是不同的。

My question: Is there an efficient way to convert "A" into a single dimensional one? 我的问题:是否有一种有效的方法可以将“ A”转换为一维? 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; 从现在开始,您可以通过计算B在每个维度上的大小的适当偏移量来访问B的元素; 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. 现在,如果您正在对数组进行堆初始化,那么这将不起作用,因为所有内存都将散布在堆上,但是对于静态/堆栈分配的数组则可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM