c - 使用双指针和 malloc 读取文件

标签 c file pointers malloc 2d

所以,我正在制作康威的生命游戏。我想读取一个文件并将其保存在双指针中并分配它的内存,但我在代码块中崩溃了。 在这个世界上我将把死细胞和活细胞放进去。

**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");
}

最佳答案

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

关于c - 使用双指针和 malloc 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48307623/

相关文章:

C编程: testing oversized shift

python - 将 JSON 数据导入 Python

java.lang.NullPointerException 和 java.net.SocketException

c - 传递给 C 函数的指针值不正确

c++ - libgphoto2和Visual Studio 2019

c - 在 Linux 中禁用磁盘缓存

c - struct typedef 中的声明规则

linux - 为本地文件设置到期日期 - Windows/Linux

c# - 为什么我的文件数组不是按数字顺序排列的?

c++ - 错误 : pointer being freed was not allocated