C中的malloc 2d数组 [英] malloc 2d arrays in C
本文介绍了C中的malloc 2d数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一种将信息存储在2D数组中的结构:
I have a structure to store information in a 2D array:
struct slopes {
int size;
int ** slope_array;
};
我为结构分配了所需的内存(数组的尺寸为s * s):
I malloc the required memory for the structure(the array has dimensions of 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);
}
但是这些行似乎会引发细分错误:
But lines such as these seem to throw segmentation errors:
slope->slope_array[0][0]=3;
有人可以看到我在做什么吗?
Can someone see what I'm doing wrong?
推荐答案
在您的 for
循环中,您需要初始化 slope-> slope_array [i]
,而不是 slope-> slope_array
:
In your for
loop, you need to initialize slope->slope_array[i]
, not slope->slope_array
:
for (i = 0; i < s; i++) {
slope->slope_array[i] = malloc(sizeof(int)*s);
}
注意:如果您已将来自 malloc
的返回调用转换为 int *
,则编译器会警告您有关此错误的信息...
Note: if you had cast the return call from malloc
to an int *
, the compiler would have warned you about this error...
这篇关于C中的malloc 2d数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文