返回信息流对于联合union,理论上来讲当然是公用存储空间,但是却没有真正使用过,理解不够深,所以写了下面的代码,编译不过,各位帮个忙,为什么不对呢?
代码如下:
#include "stdio.h"
#include "stdlib.h"
typedef struct name{
char* first;
char* second;
}student;
typedef struct id{
int id_1;
char* id_name;
}num;
typedef union person{
student student_p;
num num_p;
}who;
int main()
{
struct student* student_who=(student *)malloc(sizeof(struct name));
student_who->first=(char *)malloc(sizeof(char)*3);
student_who->first="li";
student_who->second=(char *)malloc(sizeof(char)*3);
student_who->second="si";
struct num* num_who=(num *)malloc(sizeof(struct id));
num_who->id_1=1;
num_who->id_name=(char *)malloc(sizeof(char)*7);
num_who->id_name="li si";
union who* i=(who *)malloc(sizeof(struct person));
i->student_p=student_who;
printf("I am=%s + %s",i->first,i->second);
i->num_p=num_who;
printf("I am=%d + %s",i->id_1,i->id_name);
getch();
}
有好几个错误,希望有同学帮我解决下这个困惑。
这是一条镜像帖。来源:北邮人论坛 / cpp / #74102同步于 2013/9/30
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
关于union
xiu062458
2013/9/30镜像同步5 回复
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
#include "stdio.h"
#include "stdlib.h"
typedef struct name{
char* first;
char* second;
}student;
typedef struct id{
int id_1;
char* id_name;
}num;
typedef union person{
student * student_p;
num* num_p;
}who;
int main()
{
student* student_who=(student *)malloc(sizeof(struct name));
student_who->first=(char *)malloc(sizeof(char)*3);
student_who->first="li";
student_who->second=(char *)malloc(sizeof(char)*3);
student_who->second="si";
num* num_who=(num *)malloc(sizeof(struct id));
num_who->id_1=1;
num_who->id_name=(char *)malloc(sizeof(char)*7);
num_who->id_name="li si";
who* i=(who *)malloc(sizeof(union person));
i->student_p=student_who;
printf("I am=%s + %s",i->student_p->first,i->student_p->second);
i->num_p=num_who;
printf("I am=%d + %s",i->num_p->id_1,i->num_p->id_name);
getch();
}
哦,知道了。
是这样,先要理解typedef struct 和 struct的区别。typedef struct a{}b; 中的b代表 typedef struct,表示一个类型,要定义一个结构体x,可以用struct a x;或b x;
另外,结构体可以定义为一个结构体指针,如:struct a* x;或者 b* x;
只有当给指针变量赋值前需要用malloc分配内存,使用完后记得free。
【 在 xiu062458 的大作中提到: 】
: 哦,知道了。
: 是这样,先要理解typedef struct 和 struct的区别。typedef struct a{}b; 中的b代表 typedef struct,表示一个类型,要定义一个结构体x,可以用struct a x;或b x;
: 另外,结构体可以定义为一个结构体指针,如:struct a* x;或者 b* x;
: ...................
加油!看你这么煞费苦心钻研union的劲头,有前途!
差的远呢,这是最基础的东西,自己现在还没搞清楚,真是汗颜。。。
【 在 fentoyal 的大作中提到: 】
: 加油!看你这么煞费苦心钻研union的劲头,有前途!
【 在 xiu062458 的大作中提到: 】
: 差的远呢,这是最基础的东西,自己现在还没搞清楚,真是汗颜。。。
:
union不基础,精通union的人太少了,因为这玩意太少出厂了。。。我是打从课本学过就从没用过它。。不过估计跟我不做特底层的东西有关。