The code in question is intended to load data from a txt file that will be used later on to play a console version of Conways Game of Life. The datatype is a 2D array of strings so that further iterations of the game of life can be stored in order to check for oscillating patterns. It passes the array to the "readworld" function by reference. It loads the number of iterations, width and height of the future array from the top of the text file.
The issue with this code is that it loads from the text file and saves it successfully inside the "loadWorld" function. This is proved by printing the output at the end of the function. But when that same array is accessed in the "main" function, a segmentation fault occurs at the first element.
This is weird because memory allocated by malloc is supposed to be allocated on the heap and thus assessable for other functions unless I'm missing something...
Im not sure if I should post the text file but if I should, leave a comment and it will be posted.
Any help would be greatly appreciated!
Notes Compiled file with MinGW 4.7.2. The first line of the text file contains the number of columns, rows and iterations to perform of GOL. An x in the text file represents a live cell whilst a space represents a dead cell.
#include <stdio.h>
#include <stdlib.h>
void readworld(char ***,int *,int *,int*);
int main(){
int rows,columns,ticks,repetition,count,count2;
char ***world;
readworld(world,&rows,&columns,&ticks);
printf("Rows: %i Columns: %i Ticks: %i\n",rows,columns,ticks);
for(count = 1; count < rows-1; count++){
//Segmentation fault occurs here.
printf("%s",world[0][count]);
}
system("PAUSE");
return 0;
}
void readworld(char ***world,int *rows,int *columns,int *ticks){
FILE *f;
int x,y;
//Load the file
f=fopen("world.txt","r");
//Load data from the top of the file.
//The top of the file contains number of rows, number of columbs and number of iterations to run the GOL
fscanf(f,"%i %i %i\n", rows, columns, ticks);
printf("%d %d %d\n",*rows, *columns, *ticks);
*columns=*columns+2; //Includes new line and end of line characters
world=(char***) malloc(*ticks*sizeof(char**)); //makes an array of all the grids
for (y=0;y<*ticks;y++){
world[y]=(char**) malloc(*rows * sizeof(char*)); //makes an array of all the rows
for (x=0;x<*rows;x++){
world[y][x]=(char*) malloc( *columns * sizeof(char)); //makes an array of all the collumns
}
}
for (y=0;y<*rows;y++){
fgets(world[0][y],*columns,f); //fills the array with data from the file
}
//Correctly prints the output from the textfile here
for (y = 0 ; y < *rows; y++)
printf("%s",world[0][y]);
}