C基础—函数指针,联合体,枚举,结构体和结构体指针

函数指针
//函数指针
//定义一个函数
int add(int x, int y){
    return x + y;
}
void main(){
    //定义函数指针
    int(*android)(int, int);

    android = add;
    int result = android(3, 5);
    printf("result==%d\n", result);
    getchar();
}

联合体

//定义一个联合体,特点,所有的字段都是使用同一块内存空间; 
union Max{
    long i; //4个字节 
    int k; //4个字节 
    char ii;//1个字节 
};
void main(){
    printf("max:%d\n", sizeof(union Max));

    //实验
    union Max m;
    m.k = 123;
    m.i = 100;
    printf("m.i=%d\n", m.i);
    printf("m.k=%d\n", m.k);
    getchar();
}

枚举

//枚举
enum WeekDay {
    Monday=10, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday//默认从零开始加,若Monday=10,Saturday则为16
};
void main(){
    enum WeekDay day = Wednesday;
    printf("%d\n", day);
    getchar();
}

别名

typedef int i;
typedef long l;
typedef float f;
void main(){
    i m = 10;
    l n = 123123123;
    f s = 3.1415;
    printf("%d\n", m);
    printf("%ld\n", n);
    printf("%f\n", s);
    system("pause");
}

结构体

//结构体
struct student
{
    int age;//4个字节
    float score;//4个字节
    char sex;//1个字节
};

void main(){
    //使用结构图
    struct student stu = { 18, 98.9, 'W' };
    //结构体取值 
    printf("stu.age==%d\n", stu.age);
    printf("stu.score==%.1f\n", stu.score);
    printf("stu.sex==%c\n", stu.sex);
    //结构体赋值
    stu.age = 20;
    stu.score = 100;
    stu.sex = 'M';
    printf("stu.age==%d\n", stu.age);
    printf("stu.score==%.1f\n", stu.score);
    printf("stu.sex==%c\n", stu.sex);
    //结构体的长度 
    //结构体的长度一定是最长的数据元素的整数倍
    printf("struct student长度==%d\n", sizeof(struct student));//12
    getchar();
}

结构体指针


//结构体指针
//定义结构
struct student{
    int age;//4个字节 
    float score;//4个字节 
    char sex;   //1个字节 
};

void main(){
    //使用结构图
    struct student stu = { 18, 98.9, 'W' };

    //结构体指针
    struct student *point = &stu;

    //二级指针
    struct student** point2 = &point;
    //取值运算(*point).age  等价于 point->age  
    printf("(*point).age ==%d\n", (*point).age);
    printf("point->age ==%d\n", point->age);
    printf("point->score ==%f\n", point->score);
    printf("point->sex ==%c\n", point->sex);

    //赋值运算
    point->age = 20;
    point->score = 100;
    point->sex = 'M';
    printf("point->age ==%d\n", point->age);
    printf("point->age ==%d\n", point->age);
    printf("point->score ==%f\n", point->score);
    printf("point->sex ==%c\n", point->sex);


    //二级结构体指针取值 (*point).age  等价于 point->age   所以  (**point).age 等价于 (*point)->age
    printf("(**point2).age ==%d\n", (**point2).age);
    printf("(*point2)->age ==%d\n", (*point2)->age);

    //二级指针赋值
    (**point2).age = 2000;
    printf("(**point2).age ==%d\n", (**point2).age);
    printf("(*point2)->age ==%d\n", (*point2)->age);
    getchar();
}

你可能感兴趣的:(C基础—函数指针,联合体,枚举,结构体和结构体指针)