I have an assignment for programming class, to dynamically allocate memory for a matrix.
Though as the title indicates, I end up with segfault. Anyone care to have a look?
At first I have two structs specified in the assignment:
Code:
typedef struct{
char current;
char next;
} cell;
typedef struct{
cell **field;
int rows;
int cols;
} game;
int main(...){
game data;
setupGeneration(data);
....
}
I call upon the function setupGeneration which opens a file that looks like this for example. I want all lines except for the first to be put into the matrix data.field.current
3,3
0x0
x0x
0x0
(The first line sets the size of data.rows and data.cols.)
Code:
void **setupGeneration (char **argv, game data){
int i,j, line = 0;
char c;
FILE *fileOpen;
fileOpen = fopen(argv[1], "r");
data.field = calloc(data.rows,sizeof(char *));
for(i = 0; i < data.rows; i++){
data.field[i] = calloc(data.cols, sizeof(char));
}
/* segfault? */
while(c != EOF){
c = fgetc(fileOpen);
if(c == '\n'){
line++;
}
if(line >= 1){
data.field[i][j].current = c;
printf("%c",c);
}
}
printf("\n");
return 0;
}
As you can see, I've marked the section I believe is causing the segfault.
Very thankful for any help.