我必须从文件中读取迷宫并将其存储在二维数组中。 我正在阅读的字符存储在 .txt 文件中,如下所示:
######
#....#
#..#.#
. .#..
######
请注意,行数和列数可能因文件而异。 到目前为止我阅读文件的方法:
#include <stdio.h>
#include <stdlib.h>
void read_arr(char** a, int x_size, int y_size) {
int i, j;
int tmp;
FILE* file = fopen("lab1.txt", "r");
for (i = 0; i < y_size; i++) {
for (j = 0; j < x_size; j++) {
if (tmp = fgetc(file))
a[j][i] = tmp;
printf("Success\n");
}
}
}
void print_arr(char** a, int x_size, int y_size) {
int i, j;
for (i = 0; i < x_size; i++) {
for (j = 0; j < y_size; j++) {
printf("%c", a[i][j]);
}
printf("\n");
}
}
int main() {
int x_size, y_size;
printf("What is the size of the maze (<x> <y>)? ");
scanf("%d %d", &x_size, &y_size);
printf("Maze has size %dx%d\n", x_size, y_size);
char** a = malloc(sizeof(char) * (x_size * y_size));
if (!a)
return -1;
printf("Successfully allocated memory!\n");
read_arr(a, x_size, y_size);
print_arr(a, x_size, y_size);
return 0;
}
但是我从这里得到的只是一个内存错误(恐怕我不能给出确切的错误消息,因为它是用德语显示的)。 我尝试过的另一件事是使用 fscanf,但这也没有用。 我在 Ubuntu 上,使用 gcc 编译我的代码。 任何帮助将不胜感激!
最佳答案
内存分配不正确
char** a = malloc(sizeof(char) * (x_size * y_size));
我猜你想做的是
char** a = malloc(sizeof(char*) * y_size);
for(i = 0; i < y_size; ++i)
a[i]=malloc(x_size);
同样在 read_arr 函数中,您访问数组作为 arr[j][i],而 j 是您的内部索引,而 i 是外部
for (i = 0; i < y_size; i++) {
for (j = 0; j < x_size; j++) {
if (tmp = fgetc(file))
a[j][i] = tmp; ==> a[i][j] = tmp;
printf("Success\n");
}
}
关于c - 从文本文件中读取多行字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21076071/