从堆栈和堆中获取二维数组的函数

function to get 2d-arrays from stack and heap

考虑一个简单的结构,Foo,它包含一个指向其他结构的指针,Baz。和一个二维数组,(堆栈分配):
Foo arr[ARR_SIZE][ARR_SIZE];

接下来,考虑一个函数,其中 mallocs(显然在堆中)是 Foos 的新二维数组的内存。一段代码:

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]) 之间应该没有区别,但两种方式都有问题。

所以我的问题是,函数如何处理两个数组,stack/heap 已分配?

谢谢。

如果您尝试在 c 或 c++ 中执行此操作:

 int test[][];

你会得到这个错误:

error: declaration of 'test' as multidimensional array must have bounds for all dimensions except the first

这是因为测试实际上并不像您期望的那样双关语。但是编译器将其转换为单个数据块。还有这个: 内部测试[XSIZE][YSIZE]; int n = test[x][y];

会被转换成这样:

int test[XSIZE*YSIZE];
n = test[YSIZE*x + y];

为了解决这个问题,我认为@BLUEPIXY 已经在评论中提出了解决方案。 另外,看看 this question