通过引用将动态二维数组传递给另一个函数来分配动态二维数组
Allocate a dynamic 2d-array by passing it to another function by reference
这个问题基于之前提出的两个问题:C++ Passing a dynamicly allocated 2D array by reference & C - Pass by reference multidimensional array with known size
我尝试使用前面这些问题的答案为二维数组分配内存,但内存从未分配,每次尝试访问数组时我都会收到 BAD_ACCESS 错误!
这是我的:
const int rows = 10;
const int columns = 5;
void allocate_memory(char *** maze); //prototype
int main(int argc, char ** argv) {
char ** arr;
allocate_memory(&arr) //pass by reference to allocate memory
return 0;
}
void allocate_memory(char *** maze) {
int i;
maze = malloc(sizeof(char *) * rows);
for (i = 0; i < rows; ++i)
maze[i] = malloc(sizeof(char) * columns);
}
首先你应该注意到在 C 中没有按引用传递,只有按值传递。
现在,您需要为 maze[0]
(或 *maze
)分配内存
*maze = malloc(sizeof(char *) * rows);
然后
for (i = 0; i < rows; ++i)
(*maze)[i] = malloc(sizeof(char) * columns);
这个问题基于之前提出的两个问题:C++ Passing a dynamicly allocated 2D array by reference & C - Pass by reference multidimensional array with known size
我尝试使用前面这些问题的答案为二维数组分配内存,但内存从未分配,每次尝试访问数组时我都会收到 BAD_ACCESS 错误!
这是我的:
const int rows = 10;
const int columns = 5;
void allocate_memory(char *** maze); //prototype
int main(int argc, char ** argv) {
char ** arr;
allocate_memory(&arr) //pass by reference to allocate memory
return 0;
}
void allocate_memory(char *** maze) {
int i;
maze = malloc(sizeof(char *) * rows);
for (i = 0; i < rows; ++i)
maze[i] = malloc(sizeof(char) * columns);
}
首先你应该注意到在 C 中没有按引用传递,只有按值传递。
现在,您需要为 maze[0]
(或 *maze
)分配内存
*maze = malloc(sizeof(char *) * rows);
然后
for (i = 0; i < rows; ++i)
(*maze)[i] = malloc(sizeof(char) * columns);