程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 實例介紹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);
 
}

/*
很多人對於結構的用法不是很熟悉,尤其是結構的嵌套和結構指針,在這裡寫幾個示例,希望有所幫助
*/

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved