在C中将多维数组转换为单维 [英] convert multidimensional array to single dimensional in C
问题描述
如果我在C中定义的数组如下:
If I had an array defined as follows in C:
int B[d1][d2][d3][d4][d5][d6][d7][d8][d9];
然后很容易将"B"转换为一维.但是如果我在C中有一个数组,定义如下:
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(...)
{
...
}
}
其中"A"在每个维度上的尺寸都非常大,并且对于"A"的所有内部阵列/子阵列都将是不同的.
Where "A" will have very large sizes for every dimension and they will all be distinct for all the innerarrays/subarrays of "A".
我的问题:是否有一种有效的方法可以将"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;
从现在开始,您可以通过计算每个维度中相应大小的偏移量来访问 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];
这篇关于在C中将多维数组转换为单维的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!