结构2D阵列段故障C

时间:2018-12-01 23:58:48

标签: c arrays dynamic struct segmentation-fault

我想创建一个在每个单元格中包含2条信息的矩阵,所以我决定做一个二维结构。更重要的是,我必须为该任务动态分配内存。 当我运行以下代码时,程序最终会出现“分段错误(内核已转储)”...。我尝试使用printf()进行调试,并且在调用createMap(R,地图)。

这是我的代码:

#include "functions.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Maps {
    int height;
    int gloves;
};

void read (int *R, int *P) {
    scanf("%d%d", R, P);
}

void createMap (int *R, struct Maps **map) {

    free(map);
    map = calloc (2 * (*R) + 1, sizeof(struct Maps *));
    for (int i = 0; i < 2 * (*R) + 1; ++i) {
    map[i] = calloc (2 * (*R) + 1, sizeof(struct Maps));
    }

    for (int i = 0; i < 2 * (*R) + 1; ++i)
    {
        for (int j = 0; j < 2 * (*R) + 1; ++j)
        {
            map[i][j].height = i + j;
            map[i][j].gloves = i + j;
        }
    }

}

int main () {
    int *R = malloc (sizeof(int));
    int *P = malloc (sizeof(int));
    struct Maps **map = malloc (sizeof(struct Maps *));
    read (R, P);   // work

    createMap (R, map); // kind of executes but there are no data stored  
    printf("%d\n", map[0][0].height);

    free (R);
    free (P);
    return 0;
}

// code on pastebin: https://pastebin.com/v77FbttE

1 个答案:

答案 0 :(得分:0)

  1. C在函数调用上使用值语义。您正在传递地图,但没有收到返回的指针,因此实际上您正在检查的是旧分配的地图,而不是重新分配的地图。
  2. 在调用函数时应使用引用: int R,P; struct Maps ** map;

    阅读(&R &P );

    createMap( R &map );

并相应地定义功能。在createMap中-* map = ...