C语言结构体笔记

typedef给结构起别名

可以是匿名结构或者普通的结构,方便后面使用。

#include<stdio.h>
typedef struct{ //匿名结构
    float tank_capacity;
    int tank_psi;
    const char *suit_material;
} equipment;   //结构的别名

typedef struct scuba{ //结构名
    const char *name;
    equipment kit;
} diver;

void badge(diver d){
    //使用“点表示法”访问结构的值,不能使用下标
    printf("Name:%s Tank:%2.2f(%i) Suite:%s
",d.name,d.kit.tank_capacity,d.kit.tank_psi,d.kit.suit_material);

};

int main(){
    diver randy = {"Randy",{5.5,3500,"Neoprene"}};
    badge(randy);
    return 0;
}

给结构的元素赋值

在C语言中,当为结构赋值时,计算机会复制结构的值。所以需要结构指针

typedef sturct{
  const char *name;
  int age;
} turtle;

turtle t={"lisa",12}

(*t).age和*t.age含义不同
t.age等于(t.age),它代表这个存储器单元中的内容。
为了方便阅读通常将(*t).age写作另一种形式
(*t).age==t->age
t->age表示"由t指向结构中的age字段"。

指定初始化器的方式

#include<stdio.h>
typedef struct{
    const char* color;
    int gears;
    int height;
} bike;

int main(){
    bike b= {.height=3,.color="red"}; 
    printf("%d
",b.height);
    printf("%s
",b.color);
    printf("%d
",b.gears);
    return 0;
}

我们还可以通过.属性名的方式指定初始化器,对指定对象赋值,其他的不变

原文地址:https://www.cnblogs.com/c-x-a/p/11527638.html