简体   繁体   中英

seg fault when I try to create a 2d array of structs

Why would I be getting a seg fault at the highlighted line. Am I accessing the 2d array wrong? tempMap is a 1d array with all the values for the 2d array, for example [0,1,0,0,0,0,1,0] and since I know the number of rows and columns I am trying to make it into a 2d array of Spaces (which is my struct). Any help is very much appreciated.

int opt;
char *filename = NULL;
Space **map;
char *tempMap;

   if (i != 0){
        int col = getCol(filename);
        int row = getRow(filename, col);
        printf("%d x %d\n", row, col);
        map = create_map(row, col, filename);
        tempMap = populate_map(map, filename);
        int curIndx=0;
        for (int l = 0; l < 100; ++l) {
            printf("%c", tempMap[l]);
        }
        for (int j = 0; j < row; ++j) {
            for (int k = 0; k < col; ++k) {
                map[j][k] = makeNewSpace(tempMap[curIndx],row,col); //<-----------This Line
                curIndx++;
            }
        }
    }

Also here is the makeNewSpace()

Space makeNewSpace(char character, int row, int column){
    Space space;
    space.character = character;
    space.isVisited = false;
    space.row= row;
    space.column = column;
    return space;
}

And this is where I allocate space for the 2d array.

Space **create_map( int row, int col, char *fileName) {
    Space *values = calloc(row * col, 2* sizeof(char) + (4 * sizeof(int)));
    Space **map = malloc(row * sizeof(char *));
    for (int i = 0; i < row; ++i) {
        map[i] = values + i * col;
    }
    return map;
}

Lastly here is my struct

typedef struct Space{
    char character;
    bool isVisited;
    int row;
    int column;
}Space;

Not sure if this is what you're going for, a dynamically allocated 2d array of Space structs.

#include <stdio.h>
#include <stdlib.h>

// Space struct definition
typedef struct {
    int data;
} Space;

int main() {
    int i;

    // Allocate memory for the rows
    Space** space2d = malloc(sizeof(Space*) * 3);

    // Allocate memory for the columns
    for(i = 0; i < 3; ++i) {
        space2d[i] = malloc(sizeof(Space) * 5);
    }

    // Example setting one of the struct's members inside the 2d array
    space2d[0][0].data = 100;

    printf("%d\n", space2d[0][0].data);

    // Freeing the 2d array
    for(i = 0; i < 3; ++i)
        free(space2d[i]);

    free(space2d);
}

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