【发布时间】:2018-11-05 13:28:53
【问题描述】:
这个简单的代码崩溃(分段错误),我不明白为什么。似乎这个 [] 操作不适用于结构数组。也许有人知道这种奇怪行为背后的原因。
#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);
}
【问题讨论】: