您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
053第十章 结构体与共用体01(新版)
发布时间:2021-05-06 15:16:41编辑:雪饮阅读()
看圖下定義
首先定义一个结构date,由month(月)、day(日)、year(年) 三个成员组成。
在定义并说明变量 boy1 和 boy2 时,其中的成员birthday被说明为data结构类型。成员名可与程序中其它变量同名,互不干扰。
實現
#include <stdio.h>
void main()
{
struct date
{
int month;
int day;
int year;
};
struct
{
int num;
char name[20];
char sex;
struct date birthday;
float score;
} boy1, boy2;
printf("Please input birthday(YY:) ");
scanf("%d", &boy1.birthday.year);
printf("Please input birthday(MM:) ");
scanf("%d", &boy1.birthday.month);
printf("Please input birthday(DD:) ");
scanf("%d", &boy1.birthday.day);
printf("\n");
boy2 = boy1;
printf("boy1's birthday is %d-%d-%d\n", boy1.birthday.year, boy1.birthday.month, boy1.birthday.day);
printf("boy2's birthday is %d-%d-%d\n", boy2.birthday.year, boy2.birthday.month, boy2.birthday.day);
}
D:\cproject>gcc main.c -o m
D:\cproject>m.exe
Please input birthday(YY:) 1992
Please input birthday(MM:) 02
Please input birthday(DD:) 04
boy1's birthday is 1992-2-4
boy2's birthday is 1992-2-4
結構躰是一個複合數據類型
這在上面的示例中可以體現出來,可以在看看下面這個實例
#include <stdio.h>
void main()
{
struct student
{
int num;
char *name;
char sex;
float score;
} boy1, boy2;
boy1.num = 007;
boy1.name = "Jane";
printf("Please input sex and score\n");
scanf("%c %f", &boy1.sex, &boy1.score);
boy2 = boy1;
printf("Number = %d\nName = %s\n", boy2.num, boy2.name);
printf("Sex = %c\nScore = %f\n", boy2.sex, boy2.score);
}
D:\cproject>m.exe
Please input sex and score
g 23
Number = 7
Name = Jane
Sex = g
Score = 23.000000
結構體變量的引用
可以引用结构体变量成员的地址,也可以引用结构体变量的地址
實例如:
#include <stdio.h>
void main()
{
struct student
{
int num;
char *name;
char sex;
float score;
} boy1;
boy1.num = 007;
boy1.name = "Jane";
/*
%0 无符号以八进制表示的整数
*/
printf("The address of struct is %o :\n", &boy1 );
printf("The address of num is %o :\n", &boy1.num );
printf("The address of struct is(16) %p :\n", &boy1 );
printf("The address of num is(16) %p :\n", &boy1.num );
}
D:\cproject>gcc main.c -o m
D:\cproject>m.exe
The address of struct is 30377000 :
The address of num is 30377000 :
The address of struct is(16) 000000000061FE00 :
The address of num is(16) 000000000061FE00 :
有一個疑問,爲什麽結構躰地址用8進制輸出?一般地址不都是用16進制輸出的嗎?
只是例子而已?沒有意義?
谁说没有意义的,linux、unix中很常见啊,windows中八进制和十六进制也不少
或者说八进制和十六进制的好处是熟练者可以一眼看出相关含义,比如unix、linux中的文件属性(八进制),硬件相关的字节、地址什么的。
关键字词:結構體
上一篇:052第九章 预处理03(新版)
相关文章
-
无相关信息