You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

结构体数组赋值操作失败引发段错误,求问题原因解析

Segmentation Fault in Struct Array Access: Explained and Fixed

Let's break down exactly why you're hitting that segmentation fault—it all comes down to a common pointer mistake in your foo function:

The Root Cause

Your out parameter is a qwe **—a pointer to a pointer. Its job is to let you modify the value of p in main (since C uses pass-by-value, you need a pointer to the pointer to change where it points).

After you do *out = malloc(SIZE*sizeof(qwe));, *out correctly points to the start of your newly allocated array of qwe structs. But here's the mistake:

out[i]->a = i; // Wrong!

out is a pointer to a pointer, so out[i] treats it as an array of pointers—not the array of structs you just allocated. Each out[i] skips sizeof(qwe*) bytes, which takes you way outside the memory you own, causing the segfault.

The Fix

You need to first dereference out to get the struct array pointer (*out), then access its elements with [i]:

(*out)[i].a = i;
(*out)[i].b = strdup("Hello");

Alternatively, you could use pointer arithmetic: ((*out) + i)->a = i;, but the array syntax is more readable.

Corrected Full Code

I also added memory cleanup to avoid leaks—always free what you allocate!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 3
typedef struct{
 int a;
 char * b;
}qwe;
void foo ( qwe **out){
 int i;
 *out = (qwe*)malloc(SIZE*sizeof(qwe));
 for (i=0;i<SIZE;i++){
 (*out)[i].a = i;
 (*out)[i].b = strdup("Hello");
 }
}
int main() {
 int i = 0;
 qwe *p = NULL;
 foo(&p);
 for (i=0;i<SIZE;i++)
 printf("Int: %d, str: %s \n",p[i].a , p[i].b);
 // Clean up allocated memory
 for (i=0;i<SIZE;i++){
 free(p[i].b);
 }
 free(p);
 return 0;
}

内容的提问来源于stack exchange,提问作者DMykhail

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:56:52