考虑一个简单的结构,Foo
,它包含一个指向其他结构的指针,Baz
。和一个二维数组,(堆栈分配):
Foo arr[ARR_SIZE][ARR_SIZE];
接下来,考虑一个函数,它 malloc
(显然在堆中)为新的 Foo
二维数组提供内存。一段代码:
Foo** arr_copy = malloc(sizeof(Foo*) * ARR_SIZE);
for (int i = 0; i < ARR_SIZE; i++)
{
arr_copy[i] = malloc(sizeof(Foo) * ARR_SIZE);
}
for (int i = 0; i < ARR_SIZE; i++)
{
for (int j = 0; j < ARR_SIZE; j++)
{
arr_copy[i][j].baz = malloc_baz();
}
}
现在,在我的项目中,我有各种函数需要处理原始数组(堆栈分配)和副本(堆分配)
问题是,当我将副本传递给某个迭代二维数组并打印一些信息的函数时,事情变得古怪(内存看起来已损坏)。
基本上,我知道之间应该没有区别:void fun(Foo** arr)
到 void fun(Foo arr[ARR_SIZE][ARR_SIZE])
但两种方式都有问题。
所以我的问题是,一个函数如何处理两个数组,堆栈/堆分配?
谢谢。
最佳答案
如果您尝试用 C 或 C++ 执行此操作:
int test[][];
你会得到这个错误:
error: declaration of 'test' as multidimensional array must have bounds for all dimensions except the first
这是因为 test 实际上并不像您期望的那样双关语。但是编译器将其转换为单个数据 block 。和这个: 内部测试[XSIZE][YSIZE]; int n = test[x][y];
会被转换成这样:
int test[XSIZE*YSIZE];
n = test[YSIZE*x + y];
为了解决这个问题,我认为@BLUEPIXY 已经在评论中提出了解决方案。 另外,看看 this question .
关于c - 从堆栈和堆中获取二维数组的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30810490/