goz*_*lli 2 c malloc pointers multidimensional-array
我正在尝试在C程序中分配2d数组.它在这样的主要功能工作正常(如解释在这里):
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char ** argv)
{
int ** grid;
int i, nrows=10, ncols=10;
grid = malloc( sizeof(int *) * nrows);
if (grid == NULL){
printf("ERROR: out of memory\n");
return 1;
}
for (i=0;i<nrows;i++){
grid[i] = malloc( sizeof(int) * ncols);
if (grid[i] == NULL){
printf("ERROR: out of memory\n");
return 1;
}
}
printf("Allocated!\n");
grid[5][6] = 15;
printf("%d\n", grid[5][6]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但由于我必须使用不同的数组多次这样做,我试图将代码移动到一个单独的函数中.
#include <stdio.h>
#include <stdlib.h>
int malloc2d(int ** grid, int nrows, int ncols){
int i;
grid = malloc( sizeof(int *) * nrows);
if (grid == NULL){
printf("ERROR: out of memory\n");
return 1;
}
for (i=0;i<nrows;i++){
grid[i] = malloc( sizeof(int) * ncols);
if (grid[i] == NULL){
printf("ERROR: out of memory\n");
return 1;
}
}
printf("Allocated!\n");
return 0;
}
int main(int argc, char ** argv)
{
int ** grid;
malloc2d(grid, 10, 10);
grid[5][6] = 15;
printf("%d\n", grid[5][6]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,虽然在分配时没有抱怨,但在访问阵列时会出现分段错误.我阅读了关于衰变数组和类似主题的不同帖子,但我仍然无法弄清楚如何解决这个问题.我想我没有正确地将2d数组传递给函数.
非常感谢.
那不是一个多维数组; 它是一个包含指向单维数组指针的单维数组.多维数组不包含指针; 它们是单个内存块.
你的问题是你有一个指针指针,你试图通过参数从函数返回它.如果您要这样做,您将需要一个指向指针的指针作为您的参数,并且您将不得不将指针的地址传递给指向该方法的指针.如果你不这样做,你不改变变量的值grid在main-你改变它被复制作为参数的一个malloc2d功能.因为gridin main未被初始化,所以会得到未定义的行为.
以下是我的修复示例:
#include <stdio.h>
#include <stdlib.h>
int malloc2d(int *** grid, int nrows, int ncols){
int i;
*grid = malloc( sizeof(int *) * nrows);
if (*grid == NULL){
printf("ERROR: out of memory\n");
return 1;
}
for (i=0;i<nrows;i++){
(*grid)[i] = malloc( sizeof(int) * ncols);
if ((*grid)[i] == NULL){
printf("ERROR: out of memory\n");
return 1;
}
}
printf("Allocated!\n");
return 0;
}
int main(int argc, char ** argv)
{
int ** grid;
malloc2d(&grid, 10, 10);
grid[5][6] = 15;
printf("%d\n", grid[5][6]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
补充说明:
free在回来之前打电话给那些人.int **,并通过返回信号错误0.