c - 结构 2d 阵列 segm 故障 C

标签 c arrays dynamic struct segmentation-fault

我想创建一个在每个单元格中包含 2 个信息的矩阵,因此我决定创建一个二维结构。更重要的是,我必须为此任务动态分配内存。 当我运行以下代码时,程序以“段错误(核心转储)”结束...我尝试使用 printf() 进行调试,我发现除了调用 createMap (R, map )。

这是我的代码:

#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. C 在函数调用上使用值语义。您正在传递映射,但没有收到返回的指针,因此实际上您正在检查旧分配的映射,而不是重新分配的映射。
  2. 调用函数时应该使用引用: 整数R,P; 结构 map **map;

    阅读(&R&P);

    createMap(R, &map);

并相应地定义函数。在createMap中 - *map = ...

关于c - 结构 2d 阵列 segm 故障 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53576125/

相关文章:

c# - 动态成员表达式

c - Linux 上的 gdb 不使用 2 的补码

c - 方法内的指针和函数调用

python - 将整数列表拆分为 bin,保留索引

arrays - 为什么我收到有关 Delphi 不兼容类型(数组和动态数组)的错误?

c++ - 制作动态对象数组问题?

c - 将 select 与阻塞和非阻塞套接字一起使用的影响

c - 服务器C编程中如何比较客户端发送的数据

python - 使用 numpy 生成 tall 数组

Python3 : Cannot change variables of locals() dictionary inside a function