我试图使用char *指针声明和初始化结构。如果我做任何事情,那么编译下面的代码就会失败
thing things[] = {{3,300},{4,*text}};
Linux在尝试打印时给了我核心转储
things[1].detail.text;
当我进行单独的作业
时,它会起作用things[1].detail.text = text;
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char *text = "ABC";
char *text2;
typedef struct {
int counter;
union
{
int number;
char *text;
} detail;
} thing;
thing one;
thing two;
one.counter = 1;
one.detail.number = 100;
two.counter = 2;
two.detail.text = (char *)malloc(10 * sizeof(char));
strcpy(two.detail.text, text);
thing things[] = {{3,300},{4,*text}};
//things[1].detail.text = text;
printf("%d: %d\n%d: %s\n", one.counter, one.detail.number, two.counter, two.detail.text);
printf("%d: %d\n%d: %s\n", things[0].counter, things[0].detail.number, things[1].counter, things[1].detail.text);
return 0;
}
非常感谢任何帮助。
答案 0 :(得分:1)
使用thing things[] = {{3,300},{4,text}};