在C中为3D数组分配连续内存 [英] Allocating contiguous memory for a 3D array in C
问题描述
我需要为3D数组分配连续的空间. ()我想我应该在第一位置做到这一点,但是在实际的生产代码中,直到运行时我才知道数组的尺寸.我在下面的玩具代码中将它们作为常量提供,只是为了使事情保持简单.我知道坚持使用连续空间的潜在问题,但我只需要拥有它.我已经看到了如何对2D数组执行此操作,但是显然我不理解如何将图案扩展到3D.当我调用该函数释放内存free_3d_arr
时,出现错误:
I need to allocate contiguous space for a 3D array. () I GUESS I SHOULD HAVE MADE THIS CLEAR IN THE FIRST PLACE but in the actual production code, I will not know the dimensions of the array until run time. I provided them as constants in my toy code below just to keep things simple. I know the potential problems of insisting on contiguous space, but I just have to have it. I have seen how to do this for a 2D array, but apparently I don't understand how to extend the pattern to 3D. When I call the function to free up the memory, free_3d_arr
, I get an error:
lowest lvl
mid lvl
a.out(2248,0x7fff72d37000) malloc: *** error for object 0x7fab1a403310: pointer being freed was not allocated
如果有人能告诉我解决方法,将不胜感激.代码在这里:
Would appreciate it if anyone could tell me what the fix is. Code is here:
#include <stdio.h>
#include <stdlib.h>
int ***calloc_3d_arr(int sizes[3]){
int ***a;
int i,j;
a = calloc(sizes[0],sizeof(int**));
a[0] = calloc(sizes[0]*sizes[1],sizeof(int*));
a[0][0] = calloc(sizes[0]*sizes[1]*sizes[2],sizeof(int));
for (j=0; j<sizes[0]; j++) {
a[j] = (int**)(a[0][0]+sizes[1]*sizes[2]*j);
for (i=0; i<sizes[1]; i++) {
a[j][i] = (int*)(a[j]) + sizes[2]*i;
}
}
return a;
}
void free_3d_arr(int ***arr) {
printf("lowest lvl\n");
free(arr[0][0]);
printf("mid lvl\n");
free(arr[0]); // <--- This is a problem line, apparently.
printf("highest lvl\n");
free(arr);
}
int main() {
int ***a;
int sz[] = {5,4,3};
int i,j,k;
a = calloc_3d_arr(sz);
// do stuff with a
free_3d_arr(a);
}
推荐答案
由于您使用的是C语言,因此建议您使用真正的多维数组:
Since you are using C, I would suggest that you use real multidimensional arrays:
int (*a)[sz[1]][sz[2]] = calloc(sz[0], sizeof(*a));
这将为您的3D阵列分配连续存储.请注意,从C99开始,尺寸可以是动态的.您完全可以像使用指针数组那样访问此数组:
This allocates contiguous storage for your 3D array. Note that the sizes can be dynamic since C99. You access this array exactly as you would with your pointer arrays:
for(int i = 0; i < sz[0]; i++) {
for(int j = 0; j < sz[1]; j++) {
for(int k = 0; k < sz[2]; k++) {
a[i][j][k] = 42;
}
}
}
但是,引擎盖下没有指针数组,索引是通过指针算术和数组指针衰减的魔术来完成的.而且由于使用单个calloc()
来分配事物,因此单个free()
足以摆脱它:
However, there are no pointer arrays under the hood, the indexing is done by the magic of pointer arithmetic and array-pointer-decay. And since a single calloc()
was used to allocate the thing, a single free()
suffices to get rid of it:
free(a); //that's it.
这篇关于在C中为3D数组分配连续内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!