C_结构体和共同体

一、定义结构体三种方法:

1.先声明结构体类型再定义变量名。

2.在声明类型的同时定义变量。

3.直接定义结构体类型变量。

struct student{
    //成员列表
    int age;
    char sex;
    float score;
    NSString*name;
};



二、共同体

//引用方式:只有先定义了共同体的变量才能引用它。而且不能引用共同体变量,只能引用共同体变量中的成员
union _teacher{
  //成员列表
    int age;
    char sex;
    float score;
    NSString*name;

}teacher;


下面上完整代码

#include <stdio.h>
#include <stdlib.h>
struct File{
    char*name;
    int size;
    //与数组的区别是结构体内的数据长度可能会不一样
};


struct _My{
    char*name;
    int size;
};
typedef struct _My File2;

//简洁写法
typedef struct _Student{
    char *name;
    int age;
}Student;


Student * createStudent(char*name,int age){
    Student *s1 = malloc(sizeof(Student));
    s1->name = name;
    s1->age = age;
    return s1;
}

void deleteStudent(Student*p){
    free(p);
}


typedef  union _BaseData{
    char ch;
    uint8_t ch_num;
    uint32_t num;
    //与结构体不同的是,共同体使用同一块内存
    //共同体的长度是元素最大长度的长度,内存对齐。
}BaseData;

//内存优化压缩
typedef union _Data{
    uint8_t a;
    uint8_t b;
    uint32_t c;
    uint8_t d;
    uint64_t e;

}__attribute__((__packed__)) Data;



typedef struct _ColorARGB{
    uint8_t blue;
    uint8_t green;
    uint8_t red;
    uint8_t alpha;
    
}ColorARGB;

typedef union _Color{
    /*
     存储方式:
     小端存储:低位字节放前边,高位字节放后边
     大端存储:高位字节放前边,低位字节放后边
     */
    uint32_t color;//0xFFFEED2B 0x2B,0xED,0xFE,0xFF
    ColorARGB colorArgb;
}Color;



int main(int argc, const char * argv[]) {
    
    struct File file;
    file.name = "Sun.txt";
    file.size = 100;
    printf("FileName=%s\n",file.name);
    
    File2 myFile = {"Su.txt",2000};
    printf("filename=%s,size=%d\n",myFile.name,myFile.size);
    
    
    Student s1 = {"Sam",20};//s1是局部变量
    Student s2 = s1;
    s2.age = 30;
    
    Student *s3 = &s1;
    s1.age = 40;
    
    
    printf("s1.name=%s,s1.age=%d\n",s1.name,s1.age);//访问成员,直接用.,如果访问指针的成员,用->
    printf("s2.name=%s,s2.age=%d\n",s2.name,s2.age);
    printf("s3.name=%s,s3.age=%d\n",s3->name,s3->age);
    
    
    //面向对象的原型
    Student *s =createStudent("Zhangsan", 20);
    printf("name=%s,age=%d\n",s->name,s->age);
    deleteStudent(s);
    
    
//    BaseData data;
//    data.ch = 'B';
//    printf("ch_num is %d\n",data.ch_num);
//    printf("length of BaseData is %ld\n",sizeof(BaseData));
    
    printf("Length of BaseData is %ld\n",sizeof(Data));
    
    
    Color c;
    c.color = 0xFFFE0000;
    printf("RED=%d\n",c.colorArgb.red);
    Color c1;
    c1.color = 0xFFFEED2B;
    printf("blue=%X\n",c1.colorArgb.blue);
    
    
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值