我正在尝试使用文本文件中的字符填充二维数组(mapLayout)。
当我在读取字符时使用 printf 输出字符时,一切看起来都很好,但是将字符添加到数组的实际行似乎导致了崩溃。
#include <stdio.h>
#include <stdlib.h>
void createMap();
//height of file being read
int mapHeight, mapWidth = 20;
char mapLayout[20][20];
int main()
{
createMap();
return 0;
}
//read in string from file and populate mapLayout with chars
void createMap(){
FILE *file = fopen("map.txt", "r");
int col, row = 0;
int c;
if (file == NULL)
return NULL; //could not open file
while ((c = fgetc(file)) != EOF)
{
printf("%c", c);
printf("\nx:%d, y:%d\n", col, row);
if(c == '\n'){
row++;
col = 0;
}else{
mapLayout[col][row] = c; //<-- This line seems to be the problem
col++;
}
}
return;
}
我正在阅读的文件是 20 x 20 的地图表示。这里是:
xxxxxxxxxxxxxxxxxxxx
xA x
x x
x x
xxxxxxxxxxxxxxxx x
x x
x x
x x
x x
x x
x xxxxxxxxxxxxxxx
x x x
x x x
x x x
x x x
x x x
x xxxxxxx x
x x
x Bx
xxxxxxxxxxxxxxxxxxxx
任何帮助将不胜感激。