/*
============================================================================
Name : shownum.c
Author : liky
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
struct date { // 定义一个日期结构
int year; // 年
int month; // 月
int day; // 日
};
struct student { //定义一个学生结构,其中birthday生日为一个日期结构,也就是说结构是可以嵌套的
char *name; // 姓名
int id; // 身份证号
struct date birthday; // 生日
};
void quoteStructNormal() { // 测试结构的正常调用
struct student liky;
liky.name = "liky green";
liky.id = 7173;
liky.birthday.year = 1990;
liky.birthday.month = 10;
liky.birthday.day = 18;
printf("liky's name: %s/n", liky.name);
printf("liky's id: %d/n", liky.id);
printf("liky's birthday year: %d/n", liky.birthday.year);
printf("liky's birthday month: %d/n", liky.birthday.month);
printf("liky's birthday day: %d/n", liky.birthday.day);
}
void quoteStructPointer() { // 测试结构指针的调用
struct student lucy = {"liky", 5173, {1990, 10, 18}};
struct student *liky;
liky = &lucy;
(*liky).id = 5173;
(*liky).name = "liky";
(*liky).birthday.year = 1990;
(*liky).birthday.month = 10;
(*liky).birthday.day = 18;
printf("liky's name: %s/n", (*liky).name);
printf("liky's id: %d/n", (*liky).id);
printf("liky's birthday year: %d/n", liky->birthday.year);
printf("liky's birthday month: %d/n", liky->birthday.month);
printf("liky's birthday day: %d/n", liky->birthday.day);
}
// 这里测试结构指针
void testDatePointer() {
struct date *today;
struct date tomorrow;
// = {1990,10,18}
today = &tomorrow;
today->year = 1990;
today->month = 10;
today->day = 18;
printf("year: %d/n", (*today).year);
printf("month: %d/n", (*today).month);
printf("day: %d/n", (*today).day);
}
// 这里测试将结构指针作为参数传递
void testStructParam(struct student * stu) {
printf("stu's name: %s/n", (*stu).name);
printf("stu's id: %d/n", (*stu).id);
printf("stu's birthday year: %d/n", stu->birthday.year);
printf("stu's birthday month: %d/n", stu->birthday.month);
printf("stu's birthday day: %d/n", stu->birthday.day);
}
void main() {
//quoteStructNormal();
//quoteStructPointer();
//testDatePointer();
// 以下为测试结构数组
struct student lucy = {"liky", 5173, {1990, 10, 18}};
struct student stus[3] = {{"liky", 9173, {1990, 10, 18}},{"lucky", 5173, {1990, 10, 18}},{"lucy", 6173, {1990, 10, 18}}};
int i;
for (i=0; i<3; i++ ) {
printf("stus[%d] name: %s/n", i, stus[i].name);
printf("stus[%d]'s id: %d/n", i, stus[i].id);
printf("stus[%d]'s birthday year: %d/n", i, stus[i].birthday.year);
printf("stus[%d]'s birthday month: %d/n", i, stus[i].birthday.month);
printf("stus[%d]'s birthday day: %d/n/n/n", i, stus[i].birthday.day);
}
// 这里测试将结构指针作为参数传递
testStructParam(&lucy);
}
/*
很多人对于结构的用法不是很熟悉,尤其是结构的嵌套和结构指针,在这里写几个示例,希望有所帮助
*/