c c uni - yaokun123/php-wiki GitHub Wiki

共用体/联合体

多个变量共用同一块内存空间,同一时刻只能有一个变量起作用

一、共用体定义、赋值

使用union关键字

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
union mi{
    char a;
    short b;
    int c;
};
int main(){
    union mi tmp;
    printf("%lu\n",sizeof(tmp));//4

    tmp.a = 0x01;
    tmp.c = 0x01020304;
    tmp.b = 0x0a0b;
    printf("%#x\n",tmp.b);//0a0b
    printf("%#x\n",tmp.a);//0b
    printf("%#x\n",tmp.c);//01020a0b

    return 0;
}

二、共用体判断大小端

大端:低地址存地位、高地址存高位(服务器/网络)

小端:低地址存高位、高地址存地位(一般的小型电脑)

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
union mi{
    short b;
    char buf[2];
};
int main(){
    union mi tmp;
    tmp.b = 0x0102;
    if(tmp.buf[0] == 0x01){
        printf("big");
    }else{
        printf("little");
    }
    return 0;
}

三、枚举

将枚举类型的变量的值一一列举出来,枚举变量的值只可以赋值为{}里面的值,{}里面的值是常量

枚举{}里面列举的常量,默认是从0开始

#include<stdio.h>
enum ab {
    ONE,//默认从0开始
    TWO,
    THREE
};
enum test {
    TEST1,
    TEST2 = 5,
    TEST3
};
int main(){

    printf("%d %d %d\n",ONE,TWO,THREE);//0 1 2
    printf("%d %d %d\n",TEST1,TEST2,TEST3);//0 5 6

    //枚举的赋值
    enum ab a = TWO;
    enum test b = TEST3;
    printf("%d %d\n",a,b);//1 6
    return 0;
}

枚举实现bool类型

#include<stdio.h>
enum BOOL {false,true};
typedef enum BOOL bool;

int main(){
    printf("%d\n",false);//0
    printf("%d\n",true);//1

    bool a;
    a = false;

    printf("%d\n",a);
    return 0;
}

四、给类型取别名typedef

typedef 原类型 别名

#include<stdio.h>
typedef int u32;

int main(){

    int a = 10;
    u32 b = 10;
    printf("%d %d\n",a,b);//10 10
    return 0;
}
⚠️ **GitHub.com Fallback** ⚠️