c语言有结构体的200行代码,C语言之结构体

1 概述

结构体就是一个可以包含不同数据类型的一个结构,它是一种可以自己定义的数据类型。

2 定义结构体类型变量的方法

定义结构体变量的一般格式为:

struct 结构名

{

类型  变量名;

类型  变量名;

...

}结构变量;

代码如下:

struct Student{

char name[8];

int age;

}stu1;

上面的代码声明了一个名为Student的结构体,它包含两个成员name和age,成员name的数据类型为字符数组,成员age的数据类型位整形,同时定义了一个Student结构体变量stu1.

注意:结构体声明的时候本身不占用任何内存空间,只有当定义结构体变量的时候计算机才会分配内存。

也可以通过 struct Student 结构体变量名; 方式定义结构体变量,代码如下:

struct Student stu2 = {"Lily",19};

还可以通过typedef 形式简化,代码如下:

typedef struct Student MyStudent;

MyStudent stu3 = {"Jake",20};

完整例子如下:

#include 

int main(int argc, const char * argv[])

{

struct Student{

char name[8];

int age;

}stu1;

typedef struct Student MyStudent;

strcpy(stu1.name, "Jackz");

stu1.age = 20;

printf("姓名:%s,年龄:%d\n",stu1.name,stu1.age);

struct Student stu2 = {"Lily",19};

printf("姓名:%s,年龄:%d\n",stu2.name,stu2.age);

MyStudent stu3 = {"Jake",20};

printf("姓名:%s,年龄:%d\n",stu3.name,stu3.age);

return 0;

}

结果如下图:

9155e461e4d9becf0b97ba9db9668ec0.png

引申:链表的简单使用

#include 

int main(int argc, const char * argv[])

{

typedef struct _Node{

float score;

int age;

struct _Node *next;

}Node;

Node node1,node2,node3;

node1.score = 60.5;

node1.age = 18;

node2.score = 80.4;

node2.age = 19;

node3.score = 100.2;

node3.age = 20;

node1.next = &node2;

node2.next = &node3;

node3.next = 0;

Node curNode = node1;

printf("分数:%.1f,年龄:%d\n",curNode.score,curNode.age);

do {

curNode = *curNode.next;

printf("分数:%.1f,年龄:%d\n",curNode.score,curNode.age);

}while (curNode.next);

return 0;

}

结果如下:

0e2a6ce99b7232e32fdbcc2454e79331.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值