![](/img/trans.png)
[英]Why doesn't my C compiler warn when I assign a string literal to a non-const pointer?
[英]Why doesn't my function work to adjust my pointer's content, unless i return one to assign it
我的问题是两者之间有什么区别? 一个是空的,另一个是返回2d数组,但是它们执行相同的操作,但是功能似乎不相同吗? 我一定是在误解这里的指针。
我以为指针只存储了指向地址的地址,所以如果我将指针作为参数传递,并更改内容和指向的位置,那我不像将其重新分配给函数返回值一样。
在这两个函数的末尾,我们都打印了第一行。 但是在通过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]);
}
请注意, ft_grid_gen
不仅ft_grid_gen
更改为map
点; 它还会更改map
本身。
更改map
对呼叫者的影响不超过更改size
。 无论您在调用ft_grid_gen
用作参数的任何变量仍指向ft_grid_gen
之后的“无用”。
如果要通过参数返回值,则需要将指针传递给将接收该值的变量。
void f(int *i_ptr) {
*i_ptr = 123;
}
int i;
f(&i);
在您的情况下,这将是
void ft_grid_gen(char ***map_ptr, int size) {
...
*map_ptr = map;
}
char **map;
f(&map);
或者,您可以在外部分配内存。 由于函数不再有需要改变map
,价值map
可以直接传递。
void ft_grid_gen(char **map, int size) {
...
}
char **map = malloc(ft_sqrt(size * 4) * sizeof(char*));
ft_grid_gen(map, size);
(显然,在这种特定情况下,这种方法远非理想。)
不同之处在于,第一个函数返回的内容可供以后使用。 在第二个函数中,按值传递char**
,然后输入:
map = (char**)malloc(sq_root * sizeof(char *));
您将新值分配给局部变量map
,该局部变量map
是通过function参数分配的第一个值。 但是,这不会影响main()
的原始char**
变量-因为它是像C中的其他所有内容一样通过值传递的。如果您想更改main()
变量,则应该将指针传递给它(即char***
),并在此函数中取消引用它,例如:
*map = (char**)malloc(sq_root * sizeof(char *));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.