想要學習c語言c++卻不知道怎麼學習的同學可以直接翻到最下面。
之前有講過結構體,大家也應該知道了結構體大概的用法和作用了。
今天我們講講結構體分別和指針和數組合體會變成什麼。
結構體數組。
我們先看看下面的例子
#includestruct student{ int id; //學號 int age; //年齡 char name[20]; //姓名 char sex[5]; //性別 } stu[4] = { { 1, 15, "神奇海螺", '男' }, { 2, 15, "七彩皮皮", "女" }, { 3, 8, "小豬佩奇", "女" }, { 4, 48, "比利王", "男" }, }; int main(){ int i, number; number = sizeof(stu) / sizeof(struct student); printf("人數有%d\n", number); for (i = 0; i < number; i++){ printf("名字%s,學號為%d,性別%s,年齡%d!\n", stu[i].name,stu[i].id,stu[i].sex,stu[i].age); } getchar(); return 0; }
那麼看完大家應該也差不多知道怎麼用來吧。
下面我們再來看看數組指針,我們把輸出人員信息的放在一個函數內,然後用,指針傳參數。
#includestruct student{ int id; //學號 int age; //年齡 char name[20]; //姓名 char sex[5]; //性別 } stu[4] = { { 1, 15, "神奇海螺", '男' }, { 2, 15, "七彩皮皮", "女" }, { 3, 8, "小豬佩奇", "女" }, { 4, 48, "比利王", "男" }, }; void show(struct student *p,int lon){ int i; printf("人數有%d\n", lon); for (i = 0; i < lon; i++){ printf("名字%s,學號為%d,性別%s,年齡%d!\n", (p + i)->name, (p + i)->id, (p + i)->sex, (p + i)->age); } } int main(){ int number; number = sizeof(stu) / sizeof(struct student); show(stu,number); getchar(); return 0; }
文章到這裡就結束了,到這裡大家應該知道怎麼用了吧。還不太懂的話,拿代碼去研究研究。還不懂的可以關注後私信問我,我一般會在我發帖的這個時候回覆。不太及時請諒解。另外大家如果想學習c語言或者c++關注後私信發送“c語言”或者“c++”獲取群號。可領取學習資料,和大家一起學習交流,或有免費直播講解c\c++,和幫助答疑。
閱讀更多 明江帶你學習編程 的文章