结构体类型的定义及结构体变量的使用

定义结构体:

(1)先定义结构体类型,再定义结构体变量(推荐使用!)

struct student

{

    long number;

    char name[20];

    char sex;

    int age;

    float score[3];

};

定义结构体类型变量:

示例

struct student stu1,stu2;

(2)定义结构体类型同时定义结构体类型变量

struct student

{

    long number;

    char name[20];

    char sex;

    int age;

    float score[3];

}stu1,stu2;

也可以再定义如下变量:

示例

struct student stu3,stu4;

(3)直接定义结构体类型变量

struct

{

    long number;

    char name[20];

    char sex;

    int age;

    float score[3];

}stu1,stu2;

注意:

该方法无法记录该结构体类型,所以除直接定义外,不能再定义该结构体类型变量。

 

 

 

 

typedef+struct+指针

(1)typedef

作用:为一种数据类型定义一个新的别名。合理的数据类型包括基本数据类型(int,char等)和自定义的数据类型(struct等)。

typedef的语法:

#typedef 原类型名 新类型名

 

 

# 存在类型 别名

typedef int interger;

int x,y; <=> interger x,y; #两者等价

(2)typedef+struct 结合使用

typedef struct tagMyStruct

{ int num;

    long length;

}MyStruct;

例子

struct node

{

    int data;

    char sex;

}S1,S2;

typedef struct node SS;

#等价于

typedef struct node

{

    int data;

    char sex;

}SS;

#类型名

(3)typdef+struct+指针 结合使用

typedef struct node

{ int data;

     struct node *next;#先使用是允许的

}*pointer;

等价于

typedef struct node *pointer;#也是允许的

struct node

{ int data;

     pointer next;

};

等价于

struct node

{ int data;

     struct node *next;

};

typedef struct node *pointer;

# 结构体指针类型:指向结构体类型的类型

#最后一种是最规范的写法

 

 

结构体变量的引用:

(1)结构体变量名.成员名

#例子

printf("%d", S1.age);

(2)指向结构体的指针变量名->成员名

#例子

pointer p;#pointer本身就是一个指针类型,通过它定义的p也是指针类型

printf("%d", *p.data); 不建议

#<=>

printf("%d", p->data);

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值