一:在结构体中嵌入数组
结构体嵌入一维数组:
在结构体内放入一维数组 int score[3],给每个score赋值,并输出,如下:
#include <iostream>
using namespace std;
struct student {
char name[21];
int score[3];
};
int main() {
student zhongjiaming;
for (int i = 0; i < 3; i++) zhongjiaming.score[i] = 100 + i;
//而不是zhongjiaming[i].score
for (int i = 0; i < 3; i++)cout << zhongjiaming.score[i] << endl;
return 0;
}
输出:
学习了结构体,可以用一种更简单的方式处理二维和多维数组与函数参数的问题:
把二维或者多维数组放在结构体中,作为结构体的一个成员调用函数的时候,把结构体的地址传给函数,函数的形参用指针接收结构体的地址,这样可以绕过二维数组和多维数组传递指针的问题。
#include <iostream>
using namespace std;
struct student {
char name[21];
int score[2][3] = { 11, 12, 13, 21, 22, 23 };
};
void func(student* p) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << "p->score[" << i << "][" << j << "]=" << p->score[i][j] << endl;
}
}
}
int main() {
student zhongjiaming;
func(&zhongjiaming);
return 0;
}
输出:
二:在结构体中嵌入其他结构体
结构体不可以嵌套自己,如下(报错):
但是可以嵌套别的结构体:
(但是你得把你要嵌套的结构体放前面)
#include <iostream>
using namespace std;
struct pet {
char name[21];
char type[21];
};
struct student {
char name[21];
struct pet ;
};
int main() {
return 0;
}
初始化结构体嵌套结构体:
挨个儿赋值就行,注意归属关系。
#include <iostream>
using namespace std;
struct pet {
char name[21];
char type[21];
};
struct student {
char name[21];
struct pet pet;
};
int main() {
student zhongjiaming = { "钟佳铭", {"区哥", "duck"} };
zhongjiaming = { "钟哥", {"区哥", "duck"} };
zhongjiaming.pet = { "朱哥","rabbit" };
cout << zhongjiaming.name <<"的宠物是一只" << zhongjiaming.pet.type <<" its name is " <<zhongjiaming.pet.name << endl;
return 0;
}
输出: