c - 为什么我的函数无法调整指针的内容,除非我返回一个来分配它

标签 c pointers memory

我的问题是这两者有什么区别?一个是空的,另一个返回一个二维数组,但是它们的作用相同,但功能似乎不一样?我一定是误解了这里的指针。

我认为指针只存储了一个指向的地址,所以如果我将一个作为参数传递,并更改内容和它指向的位置,我不也会做同样的事情,将其重新分配给函数返回值。

在两个函数的末尾,我们打印第一行,他们都这样做了。但是在通过我的 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/

相关文章:

java - 一个类实现两个或多个接口(interface)是一个好习惯吗?

c - 是否有另一种方法可以在 C 中释放动态分配的内存 - 不使用 free() 函数?

c - 只读入一个或两个字符串

c - '(' token 之前的解析错误

在 C 中使用宏连接代码

c++ - 数组的地址 VS 指针到指针 : Not the same?

c++ - 运行 UNIX 应用程序的堆栈跟踪

c - 在参数中使用结构类型数据时,参数函数 C 中的结构类型未知

c - 计算一个值在数组中出现次数的最佳方法是什么?

c++ - 进程的内存分析