c语言性别可以用int型,c语言中结构体的用法

一、定义

由于一个数组中只能存放同一种类型的数据,很不方便,所以C语言允许用户自己建立由不同类型数据组成的组合型的数据结构,也就是结构体,通俗讲就像是打包封装,把一些有共同特征(比如同属于某一类事物的属性,往往是某种业务相关属性的聚合)的变量封装在内部,通过一定方法访问修改内部变量。

二、用法

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

struct student{

char no[20]; //学号

char name[20]; //姓名

char sex[5]; //性别

int age; //年龄

};

struct student stu1,stu2;

//此时stu1,stu2为student结构体变量

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

struct student{

char no[20]; //学号

char name[20]; //姓名

char sex[5]; //性别

int age; //年龄

} stu1,stu2;

当然还可以继续定义student结构体变量,如:

struct student stu3;

3、不指定类型名而直接定义结构体变量。

struct{

char no[20]; //学号

char name[20]; //姓名

char sex[5]; //性别

int age; //年龄

} stu1,stu2;

一般不使用这种方法,因为直接定义结构体变量stu1、stu2之后,就不能再继续定义该类型的变量。

4、用typedef定义结构体变量。

typedef struct stdudent

{

char name[20];

int age;

}student_t;

上面的代码,定义了一个结构体变量类型,这个类型有2个名字:第一个名字是struct student;第二个类型名字是student_t.

定义了这个之后,下面有2中方法可以定义结构体变量

第一种: struct student student_1;   //定义了一个student_1的结构体变量

第二种:student_t student_1            //定义了一个student_1的结构体变量

5、用typedef定义结构体变量,省略struct后变量名。

typedef struct

{

char name[20];

int age;

}student_t;

上面的代码,定义了一个结构体变量类型,名字为student_t ,可以用它来定义结构体变量。

student_t student_1            //定义了一个student_1的结构体变量

推荐在实际代码中使用第5种方法定义结构体变量。

三、指针的用法

typedef struct{

char name[30];

char author[20];

}BOOK;

int main()

{

BOOK *p;

BOOK a[2] = { { "Nature","Lina" },{ "Animals","Nick" } };

p = &a[0];

printf("book name: %s author: %s\n", p->name, p->author);

return(0);

}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值