Reputation: 25
I have 2x 2D arrays as a pointer. one is "int ** field" and the other one "char **mask". I want to create 2 2D arrays and initialise them. The code I have works for the int array but not for the char array, although the code is the same... why?
Minesweeper * createField(int n, int m){
Minesweeper *ms = (Minesweeper *) malloc(sizeof(Minesweeper *));
ms->m = m;
ms->n = n;
ms->field = (int **) malloc(sizeof(int *) * n);
ms->mask = (char **) malloc(sizeof(char *) * n);
for(int i=0; i<n; i++){
ms->field[i] = (int *) malloc(sizeof(int *) * m);
ms->mask[i] = (char *) malloc(sizeof(char *) * m);
}
for(int k=0; k<n; k++){
for(int j=0; j<m; j++){
ms->field[k][j] = 0;
ms->mask[k][j] = 'x';
}
}
return ms;
}
By the way:
Minesweeper is a typedef struct with 4 attributes: int** field, char** mask, int m and int n.
I always get Segmentation fault when I want to initialize my mask array...
Upvotes: 1
Views: 166
Reputation: 888
here is what you can use easily instead of your code :)
Minesweeper * createField(int n, int m){
Minesweeper *ms = (Minesweeper *) malloc(sizeof(Minesweeper));
ms->m = m;
ms->n = n;
ms->field = (int **) malloc(sizeof(int *) * n);
ms->mask = (char **) malloc(sizeof(char *) * n);
for(int i=0; i<n; i++){
ms->field[i] = (int *) malloc(sizeof(int ) * m);
ms->mask[i] = (char *) malloc(sizeof(char) * m);
}
for(int k=0; k<n; k++){
for(int j=0; j<m; j++){
ms->field[k][j] = 0;
ms->mask[k][j] = 'x';
}
}
return ms;
}
malloc declaration was not correct.
You are declaring a pointer with size of a type then you need to write as sizeof(<type>)
instead of sizeof(*<type>)
which will give size of pointer instead of the actual storage. It will solve the error :)
Upvotes: 0
Reputation: 3911
Be careful when you allocate like
malloc(sizeof(Minesweeper *));
you get memory for a single pointer allocated - (Minesweeper *)
. To allocate memory for the whole structure you have to use sizeof(Minesweeper)
- without the asterisk.
So replace with:
Minesweeper *ms = (Minesweeper *) malloc(sizeof(Minesweeper));
and
ms->field[i] = (int *) malloc(sizeof(int) * m);
ms->mask[i] = (char *) malloc(sizeof(char) * m);
Upvotes: 2