我的问题是这两者有什么区别?一个是空的,另一个返回一个二维数组,但是它们的作用相同,但功能似乎不一样?我一定是误解了这里的指针。
我认为指针只存储了一个指向的地址,所以如果我将一个作为参数传递,并更改内容和它指向的位置,我不也会做同样的事情,将其重新分配给函数返回值。
在两个函数的末尾,我们打印第一行,他们都这样做了。但是在通过我的 Main 中的 void 函数打印调整后的网格时,我遇到了段错误。
char **ft_grid_gen(int size)
{
char **map;
int index;
int elem_index;
int sq_root;
index = 0;
elem_index = 0;
sq_root = ft_sqrt(size * 4);
map = (char**)malloc(sq_root * sizeof(char *));
while (index < sq_root)
{
map[index] = (char*)malloc(sq_root * sizeof(char));
while (elem_index < sq_root)
{
map[index][elem_index] = '.';
elem_index++;
}
index++;
elem_index = 0;
}
printf("GENERATED NEW GRID of size %s!\n", map[0]);
return (map);
}
void ft_grid_gen(char **map, int size)
{
int index;
int elem_index;
int sq_root;
index = 0;
elem_index = 0;
sq_root = ft_sqrt(size * 4);
map = (char**)malloc(sq_root * sizeof(char *));
while (index < sq_root)
{
map[index] = (char*)malloc(sq_root * sizeof(char));
while (elem_index < sq_root)
{
map[index][elem_index] = '.';
elem_index++;
}
index++;
elem_index = 0;
}
printf("GENERATED NEW GRID of size %s!\n", map[0]);
}
最佳答案
不同之处在于第一个函数返回稍后可以使用的内容。在第二个函数中,您按值传入 char**
,然后使用:
map = (char**)malloc(sq_root * sizeof(char *));
您为局部变量map
分配了一个新值,该变量是通过函数参数分配的第一个值。然而,这不会影响 main()
中的原始 char**
变量——因为它像 C 中的其他内容一样按值传递。如果您想更改main()
变量,您将传递一个指向它的指针(即 char***
)并在此函数中取消引用它,例如:
*map = (char**)malloc(sq_root * sizeof(char *));
关于c - 为什么我的函数无法调整指针的内容,除非我返回一个来分配它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56094864/