我如何在C动态多维数组工作? [英] How do I work with dynamic multi-dimensional arrays in C?
问题描述
有人不知道如何用C使用动态分配的多维数组?这可能吗?
Does someone know how I can use dynamically allocated multi-dimensional arrays using C? Is that possible?
推荐答案
通过动态分配,使用malloc:
With dynamic allocation, using malloc:
int** x;
x = malloc(dimension1_max * sizeof(int*));
for (int i = 0; i < dimension1_max; i++) {
x[i] = malloc(dimension2_max * sizeof(int));
}
[...]
for (int i = 0; i < dimension1_max; i++) {
free(x[i]);
}
free(x);
此分配大小 dimension1_max
* dimension2_max
的二维数组。因此,举例来说,如果你想要一个640 * 480阵列(图像的FE像素),使用 dimension1_max
= 640, dimension2_max
= 480。然后,您可以使用<访问数组code> X [D1] [D2] ,其中 D 1
= 0 ..639, D 2
= 0..479。
This allocates an 2D array of size dimension1_max
* dimension2_max
. So, for example, if you want a 640*480 array (f.e. pixels of an image), use dimension1_max
= 640, dimension2_max
= 480. You can then access the array using x[d1][d2]
where d1
= 0..639, d2
= 0..479.
但在搜索SO或谷歌也透露出其他的可能性,例如<一个href=\"http://stackoverflow.com/questions/365782/how-do-i-best-handle-dynamic-multi-dimensional-arrays-in-c-c\">in这太问题
But a search on SO or Google also reveals other possibilities, for example in this SO question
请注意,在那种情况可能会与该承担这个职能的问题,如果你的磁盘阵列不会分配一个连续的内存区(640 * 480字节)。因此,要获得数组满足条件,与此代替上述的malloc块:
Note that your array won't allocate a contiguous region of memory (640*480 bytes) in that case which could give problems with functions that assume this. So to get the array satisfy the condition, replace the malloc block above with this:
int** x;
int* temp;
x = malloc(dimension1_max * sizeof(int*));
temp = malloc(dimension1_max * dimension2_max * sizeof(int));
for (int i = 0; i < dimension1_max; i++) {
x[i] = temp + (i * dimension2_max);
}
[...]
free(temp);
free(x);
这篇关于我如何在C动态多维数组工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!