struct Date{
int month;
int day;
int year;
}
struct stu{
int num;
char *name;
char sex;
struct Date birthday;
Float score;
}
- 在stu中嵌套存储Date结构体内容
- 注意:
- 结构体不可以嵌套自己变量,可以嵌套指向自己这种类型的指针
struct Student {
int age;
struct Student stu;
};
- 对嵌套结构体成员的访问
- 如果某个成员也是结构体变量,可以连续使用成员运算符"."访问最低一级成员
struct Date {
int year;
int month;
int day;
};
struct Student {
char *name;
struct Date birthday;
};
struct Student stu;
stu.birthday.year = 1986;
stu.birthday.month = 9;
stu.birthday.day = 10;
- 结构体虽然是构造类型, 但是结构体之间赋值是值拷贝, 而不是地址传递
struct Person{
char *name;
int age;
};
struct Person p1 = {"lnj", 35};
struct Person p2;
p2 = p1;
p2.name = "zs";
printf("p1.name = %s\n", p1.name);
printf("p2.name = %s\n", p2.name);
- 所以结构体变量作为函数形参时也是值传递, 在函数内修改形参, 不会影响外界实参
#include <stdio.h>
struct Person{
char *name;
int age;
};
void test(struct Person per);
int main()
{
struct Person p1 = {"lnj", 35};
printf("p1.name = %s\n", p1.name);
test(p1);
printf("p1.name = %s\n", p1.name);
return 0;
}
void test(struct Person per){
per.name = "zs";
}