如何在 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(*x));
for (int i = 0; i < dimension1_max; i++) {
x[i] = malloc(dimension2_max * sizeof(x[0]));
}
//Writing values
x[0..(dimension1_max-1)][0..(dimension2_max-1)] = Value;
[...]
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.然后您可以访问该数组使用 x[d1][d2]
其中 d1
= 0..639, d2
= 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 或 Google 上的搜索也揭示了其他可能性,例如 在这个问题中
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(*x));
temp = malloc(dimension1_max * dimension2_max * sizeof(x[0]));
for (int i = 0; i < dimension1_max; i++) {
x[i] = temp + (i * dimension2_max);
}
[...]
free(temp);
free(x);
这篇关于如何在 C 中使用动态多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!