chi*_*hib 0 c arrays char multidimensional-array
我试图用文本文件中的字符填充二维数组(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;
}
Run Code Online (Sandbox Code Playgroud)
我正在阅读的文件是地图的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
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激.
int col, row = 0;为什么col没有初始化为零.如果文件中的第一个字符是,\n则它不会崩溃,对于所有剩余的情况,将发生崩溃(未定义的行为).
做
int col = 0;
int row = 0;
Run Code Online (Sandbox Code Playgroud)