C语言结构体

1 结构体

数组是相同类型元素的集合。

结构体可以由多种不同类型的数据类型组成的新的数据类型

2 结构体声明

struct Student { 
    int age; 
    charchar *name;     
}; 

3 结构体变量的定义

1、先定义结构体,再定义变量

struct Student { 
    int age; 
    charchar *name; 
}; 
struct Student stu; 

2、定义结构体的同时定义变量

struct Student { 
    int age; 
    charchar *name; 
} stu; 

3、直接定义结构体变量

struct { 
    int age; 
    charchar *name; 
} stu; 

4 结构体成员

1 成员类型

任何变量类型都可以作为结构体成员。

struct List{
   int a[20];
   float b;
   long *c;
   struct List *d;    //struct List d是非法的
} ;

2 成员访问

结构体成员通过(.)操作符访问。

struct List list;
list.a;
list.b;
list.d.c;   ///操作符的优先级是从左到右

3 指针访问

void fun(struct List *p);  //指针需要进行间接访问
(*p).a;      //因为(.)操作符的优先级高于(*),所以要用括号
// ->操作符
p->a;
p->d.a;

4 不完整声明

struct B;   //不完整声明
struct A{
    struct B *b;
};
struct B{
    struct A *a;
};

A结构体中有B结构体,所以A需要B的不完整声明。

5 结构体的初始化

1、声明变量的同时初始化

struct Student {  
    int age;  
    charchar *name;  
};  
struct Student stu = {22, "hello"};  

2、先声明变量,再逐一初始化

struct Student stu;  
stu.age = 22;  
stu.name = "hello";  


3、定义结构体的同时进行变量定义和初始化 

struct Student { 
    int age; 
    charchar *name; 
} stu = {22, "hello"};
  4、非顺序初始化
struct Student stu = {.name = "hello", .age = 22};

注意:如果没有初始化结构体,所有变量会自动的有默认值

6 参数传递

typedef struct{
int a;
float b;
float c;
} A;
void printA(A a){
    printf("%d",a.a);
}
int main(){
    A a = {1};
    printA(a);
}

这样虽然正确,但是效率很低,C语言传值调用,会拷贝整一份的结构体,上例中总共要拷贝12个字节。

typedef struct{
    int a;
    float b;
    float c;
} A;
void printA(A *a){
    printf("%d",a->a);
}
int main(){
    A a = {1};
    printA(&a);
}

而这里通过指针传递的话,指针要比结构体小的多,所以效率会高。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值