使用双指针和 malloc 读取文件

Reading Files with a double pointer and malloc

所以,我正在制作 Conway.I 的 生命游戏 想要读取一个文件并将其保存在双指针中并 malloc 它是内存,但我正在代码块崩溃。 世界上我会放死细胞和活细胞

**world = (char **)malloc(grammes * sizeof(char));
for(i=0;i<grammes;i++)
    world[i]=(char *)malloc(stiles * sizeof(char));


for(i=0;i<grammes;i++)
{
    for(j=0;j<stiles;j++)
    {
        fscanf(fp,"%c",&world[i][j]);
    }
}

for(i=0;i<grammes;i++)
{
    for(j=0;j<stiles;j++)
    {
        printf("%c",world[i][j]);
    }
    printf("\n");
}

崩溃的原因是 world 是双指针,您应该首先为 world 而不是 **world 分配内存。

替换下面的语句

  **world = (char **)malloc(grammes * sizeof(char));

 world = malloc(grammes * sizeof(char*)); //since world is double pointer it should be sizeof(char*)

注意:malloc 的类型转换不需要按照此处的建议 Do I cast the result of malloc?

  1. 通过 **world 您访问的是实际值而不是地址。您必须将其更改为 world (如果您已经声明了变量)
  2. 第一行应该是sizeof(char*)因为world是一个指向char*数组的指针

好吧,问题是 - 你问这个问题是为了误导我们,而不是帮助我们帮助你。

char ** world = malloc(..);

没关系。

当你之前这样做 char** world; 然后你这样做

**world = ...

错了。因为你用了一个char来存储指针的值。

好吧,现在看看你做了什么,而不是创建一个内存块,其中包含你为 char 分配的多个 char*,然后再次使用它们中的每一个来存储 [=17] 的内存地址=] 将被存储。是的,错了

world = malloc(sizeof(char*) *grammes);

更好

world = malloc(sizeof *world * grammes);

malloc 的 return 值应该被检查并且 malloc return 是一个 void* 可以隐式转换为 char*无需转换结果。

world = malloc(sizeof *world * grammes);
if( world == NULL ){
    perror("malloc failed");
    exit(EXIT_FAILURE);
} 

还要检查 fscanf 的 return 值。您可以查看手册页或标准以了解它们的成功价值,嘿 return.


chux指出-

东西比较少但是不确定你会不会搞这些细节

malloc(sz)可以returnNULL如果sz = 0这么说mallocreturns NULL 表示错误不完全正确,或者即使 sz 是一个溢出值,它也可能 return NULL.

这里支票最好这样写

if( world != NULL && grammes != 0){
   //Error.
}