I am trying to populate a two dimensional array (mapLayout) with chars from a text file.
When I use printf to output the chars as they are being read everything looks fine, however the actual line that adds the char to the array seems to be causing a crash.
#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;
}
The file I am reading is a 20 x 20 representation of a map. Here it is:
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
Any help would be greatly appreciated.
int col, row = 0;whycolis not initialized to zero. If the first character in the file is\nthen it will not crash, for all remaining cases crash will happen (undefined behaviour).Do