我想创建一个在每个单元格中包含 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
最佳答案
- C 在函数调用上使用值语义。您正在传递映射,但没有收到返回的指针,因此实际上您正在检查旧分配的映射,而不是重新分配的映射。
调用函数时应该使用引用: 整数R,P; 结构 map **map;
阅读(&R、&P);
createMap(R, &map);
并相应地定义函数。在createMap中 - *map = ...
关于c - 结构 2d 阵列 segm 故障 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53576125/