- #include <stdio.h>
- #include <stdlib.h>
- struct S_Person {
- char * name;
- int age;
- } person, *p;
- union U_Person {
- char * name;
- int age;
- } u_person, *u_p;
- int main(void) {
- p = (struct S_Person *) malloc(sizeof(struct S_Person));
- if (p == NULL ) {
- exit(1);
- }
- p->age = 10;
- printf("age = %d\\n", p->age);
- p->name = (char *) malloc(sizeof(char) * 20);
- if ( p->name == NULL )
- {
- exit(1);
- }
- sprintf(p->name, "%s", "杨志永");
- printf("name = %s\\n", p->name);
- //释放内存的顺序与分配内存的顺序相反。不论是多少层次
- free(p->name);
- free(p);
- p = NULL;
- u_p = (union U_Person *) malloc(sizeof(union U_Person));
- if ( u_p == NULL )
- {
- exit(1);
- }
- u_p->age = 20;
- printf("union age = %d\\n", u_p->age);
- u_p->name = (char *) malloc(sizeof(char) * 20);
- if ( u_p->name == NULL )
- {
- exit(1);
- }
- sprintf(u_p->name, "%s", "yangzhiyong");
- printf("union name = %s\\n", u_p->name);
- //释放内存的顺序与分配内存的顺序相反。不论是多少层次
- free(u_p->name);
- free(u_p);
- u_p = NULL;
- return EXIT_SUCCESS;
- }
- //该片段来自于http://www.codesnippet.cn/detail/011120136883.html
来源: http://www.codesnippet.cn/detail/011120136883.html