#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/