c - C 中的 malloc 二维数组

标签 c arrays

<分区>

我有一个在二维数组中存储信息的结构:

struct slopes {
    int size;
    int ** slope_array;
};

我为结构分配了所需的内存(数组的维度为 s*s):

struct slopes * slope=malloc(sizeof(struct slopes));
slope->size=s;
slope->slope_array=malloc(sizeof(int *)*s);
int i;
for(i=0;i<s;i++) {
    slope->slope_array=malloc(sizeof(int)*s);
}

但是像这样的行似乎会引发段错误:

slope->slope_array[0][0]=3;

有人能看出我做错了什么吗?

最佳答案

在你的for循环中,你需要初始化slope->slope_array[i],而不是slope->slope_array:

for (i = 0; i < s; i++) {
    slope->slope_array[i] = malloc(sizeof(int)*s);
}

注意:如果您将返回调用从 malloc 转换为 int *,编译器会警告您此错误...

关于c - C 中的 malloc 二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20658844/

相关文章:

python - 验证体积/3D 空间中的点

java - HashMap#entrySet 抛出 ArrayStoreException

php - 将数组内爆为字符串以创建 sql 查询

c - 如何测试用 C 编写的 C 代码或库

c - 取消引用指向 pcap_t 结构的不完整类型的指针

c - 什么时候调用 fork()?

javascript - 删除重复的子数组

c - printf 命令导致段错误?

php - in_array 多个值

c - 简单的 C 双指针