Andy 胡

导航

C语言:结构体,共用体

结构体: 一个变量,存储不同类型的数据项
共用体:一个变量,存储不同类型的数据项,相同的内存位置,存储不同的数据类型

#include <stdio.h>        
#include <string.h>        
        
struct Books {        
    char  title[50];    
    char  author[20];    
};        
        
union Data {        
    char  title[50];    
    char  author[20];    
};        
main() {        
        
    union Data _u;    
    struct Books _s;    
        
    printf( "struct : %d\n", sizeof(_s));    
    printf( "union大小 : %d\n", sizeof(_u));    
        
    /*********************struct***********************/    
    strcpy( _s.title, "C Programming");    
    printf( "union:title : %s\n", _s.title);    
    strcpy( _s.author, "Andy Bob");    
    printf( "union:title : %s\n", _s.title);    
    /*********************union***********************/    
    strcpy( _u.title, "C程序设计");    
    printf( "struct:title : %s\n", _u.title);    
    // 被覆盖     
    strcpy( _u.author, "谭浩强");    
    printf( "struct:title : %s\n", _u.title);    
    return 0;    
}        

struct : 70
union大小 : 50
union:title : C Programming
union:title : C Programming
struct:title : C程序设计
struct:title : 谭浩强

posted on 2017-02-09 22:16  talkwah  阅读(263)  评论(0编辑  收藏  举报