当前位置:编程学习 > C/C++ >>

实例介绍C语言结构的用法

 */
 #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("likys name: %s ", liky.name);
 printf("likys id: %d ", liky.id);
 printf("likys birthday year: %d ", liky.birthday.year);
 printf("likys birthday month: %d ", liky.birthday.month);
 printf("likys birthday day: %d ", 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("likys name: %s ", (*liky).name);
 printf("likys id: %d ", (*liky).id);
 printf("likys birthday year: %d ", liky->birthday.year);
 printf("likys birthday month: %d ", liky->birthday.month);
 printf("likys birthday day: %d ", 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 ", (*today).year);
 printf("month: %d ", (*today).month);
 printf("day: %d ", (*today).day);
}

 // 这里测试将结构指针作为参数传递
void testStructParam(struct student * stu) {
 printf("stus name: %s ", (*stu).name);
 printf("stus id: %d ", (*stu).id);
 printf("stus birthday year: %d ", stu->birthday.year);
 printf("stus birthday month: %d ", stu->birthday.month);
 printf("stus birthday day: %d ", 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 ", i, stus[i].name);
  printf("stus[%d]s id: %d ", i, stus[i].id);
  printf("stus[%d]s birthday year: %d ", i, stus[i].birthday.year);
  printf("stus[%d]s birthday month: %d ", i, stus[i].birthday.month);
  printf("stus[%d]s birthday day: %d ", i, stus[i].birthday.day);
 }
 
 // 这里测试将结构指针作为参数传递
 testStructParam(&lucy);
 
}

/*
很多人对于结构的用法不是很熟悉,尤其是结构的嵌套和结构指针,在这里写几个示例,希望有所帮助
*/
补充:软件开发 , C语言 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,