c - C 中的结构和二维数组错误

标签 c

#include<stdio.h>
#include<stdlib.h>
typedef struct Room {
    int values[4][4];
    int size;
} Room;

int createRoom(Room *pm, char *mazefilename)
{

    FILE *input;
    FILE *output;
    pm = (Room *)malloc(sizeof(Room *));
    input = fopen(mazefilename, "r");

    int a = 0;
    int i = 0, j = 0;
    int count;

    char  line[6];


    fscanf(input, "%s", line);
    while (!feof(input)) {
        printf("Line is  %s\n", line);
        for (i = 0; i < 4; i++) {
            int c = line[i] - '0';

            pm->values[a][i] = c;
        }
        a++;
        fscanf(input, "%s", line);
    }
    fclose(input);
    return a;
}

这给我段错误-

Line is  1001
Line is  1001
Line is  1101
Segmentation fault (core dumped)

为什么它给我段错误。如果我只是打印行而不是 pm->values[a][i]=c;,它会给我正确的输出。所以我认为这行有问题-pm->values[a][i]=c;

我的输入文件是-

1001
1001
1101
1109

最佳答案

您的函数签名和 malloc 调用对于您要执行的操作是不正确的。如果你想为传入的 pm 指针分配空间,你需要传递该指针的地址:

int createRoom(Room ** pm,char *mazefilename)

然后您的 malloc() 调用必须为 Room 结构分配足够的空间,而不是 Room 指针:

*pm=malloc(sizeof(Room));

关于c - C 中的结构和二维数组错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28564870/

相关文章:

c - 做不以 C 结尾的 while 循环

c++ - 有没有办法将基数 2^64 数字转换为其字符串形式的基数 10 值,或在 C 或 C++ 中以标准输出显示它,而不使用大数字库?

c - C语言新手;在 for 循环中使用 pow()

c - 未知 "for"语句 (C)

c - 需要左值作为赋值的左操作数

c - 无法在 C 中使用 gets() 获取字符串

c - 如何通过代码重写 PIC32 引导闪存?

linux合并两个文件不重复

c - 从 fscanf 接收到奇怪的数字 - int 转换?

类型转换和整数转换混淆