I’m trying to read a map from a text file and create a string array according to the number of rows and columns in the map. Every cell in the grid is a 2 character string.
For instance,
**--**--**--
--**--**--**
should create a 2*6 matrix. The number of rows and columns are ROWS and COLS respectively. I used
char ***map = malloc(ROWS * sizeof(char *));
for (i = 0; i < ROWS; i++)
{
map[i] = malloc(COLS * sizeof(char) * 2);
}
But when I try to use a map[x][y], it will segfault.
char ***map;could be interpreted as an “Array of arrays of strings”, so the inner array actually contains char pointers. Therefore, your loop needs to look like this:Alternatively, you could declare map as
char **map, then your initialization code would work, but then you’d need to usemap[i][j]andmap[i][j+1]to access the elements of the individual cells.