简体   繁体   中英

SEGMENTATION FAULT (11) for one of my 2d arrays?

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...

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);

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM