您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
054第十章 结构体与共用体02(新版)
发布时间:2021-05-06 16:12:01编辑:雪饮阅读()
结构体变量的初始化
我们可以这么对结构体进行初始化!
#include <stdio.h>
void main()
{
struct student /*定义结构*/
{
int num;
char *name;
char sex;
float score;
}boy1, boy2 = { 102, "Jane", 'M', 98.5 };
boy1 = boy2;
printf("Number = %d\nName = %s\nScore = %d\n", boy1.num, boy1.name, boy1.score);
printf("\n\n");
printf("Number = %d\nName = %s\nScore = %d\n", boy2.num, boy2.name, boy2.score);
}
D:\cproject>m.exe
Number = 102
Name = Jane
Score = 0
Number = 102
Name = Jane
Score = 0
结构体数组
一个结构体变量中可以存放一组数据(如一个学生的学号、姓名、成绩等数据)。
如果有10个学生的数据需要参加运算,显然应该用数组,这就是结构体数组。
结构体数组与以前介绍过的数值型数组不同之处在于每个数组元素都是一个结构体类型的数据,它们都分别包括各个成员(分量)项。
一個通訊錄實例如:
#include"stdio.h"
#define NUM 3
struct person
{
char name[20];
char phone[10];
};
void main()
{
struct person man[NUM];
int i;
for( i=0; i < NUM; i++)
{
printf("input name:\n");
gets(man[i].name);
printf("input phone:\n");
gets(man[i].phone);
}
printf("name\t\t\tphone\n\n");
for( i=0; i < NUM; i++)
{
printf("%s\t\t\t%s\n",man[i].name,man[i].phone);
}
}
編譯運行結果如:
D:\cproject>gcc main.c -o m
D:\cproject>m.exe
input name:
xy1
input phone:
131...
input name:
xy2
input phone:
159...
input name:
xy3
input phone:
139...
name phone
xy1 131...
xy2 159...
xy3 139...
指向结构体类型数据的指针
一个结构体变量的指针就是该结构体变量所占据的内存段的起始地址。
可以设一个指针变量,用来指向一个结构体变量,此时该指针变量的值是结构体变量的起始地址。(指针伟大吧,指啥都行~)
指针变量也可以用来指向结构体数组中的元素。
一個具體的實例如:
#include <stdio.h>
struct stu
{
int num;
char *name;
char sex;
float score;
} boy1 = {102, "xkws", 'M', 78.5};
void main()
{
struct stu *pstu;
pstu = &boy1;
printf("original:Number = %d Name = %s", boy1.num, boy1.name);
printf(" Sex = %c Score = %f\n\n", boy1.sex, boy1.score);
printf("parenthesis:Number = %d Name = %s", (*pstu).num, (*pstu).name);
printf(" Sex = %c Score = %f\n\n", (*pstu).sex, (*pstu).score);
printf("arrow:Number = %d Name = %s", pstu->num, pstu->name);
printf(" Sex = %c Score = %f\n\n", pstu->sex, pstu->score);
}
关键字词:結構體,指針