[英]C - Segmentation Fault Assigning value to Array of Struct
I am getting segmentation fault whenever I do this.每当我这样做时,我都会遇到分段错误。 I wonder if there is a way for me to assign a value to the struct without getting SegFault?
我想知道是否有一种方法可以让我在不获取 SegFault 的情况下为结构分配值?
typedef struct _chunk
{
int lo; // lower bound
int hi; // higher bound
} chunk;
chunk_stack = (chunk **)malloc(10 * 10 * sizeof(chunk **));
for (i = 0; i < chunk_per_thread; i++)
{
chunk_stack[myid][i].lo = 0;
chunk_stack[myid][i].hi = 1;
}
Suppose you need to allocate a 2D array of size r * c
.假设您需要分配一个大小为
r * c
的二维数组。
You need to first allocate memory for the double pointer which you did but have an error in it ie, one extra * inside malloc function.您需要首先为您所做但有错误的双指针分配 memory,即在 malloc function 内有一个额外的 *。
chunk **chunk_stack = (chunk **)malloc(r * sizeof(chunk *));
Then you need to allocate memory for each of the rows separately.然后你需要为每一行分别分配 memory 。
for(int i = 0; i < r; i++){
chunk_stack[i] = (chunk*)malloc(c * sizeof(chunk));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.