#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
struct Name {
char firstName[10];
char lastName[20];
};
struct Student {
char sno[20];//学号
struct Name name;
int age;
char gender;
};
1、自我嵌套 单链表结构的结点定义如下
//方式1
struct Node {
int data;
struct Node* next;
};
//方式2
typedef struct Node {
int data;
struct Node* next;
}LNode;
2、二叉树结构的结点定义如下:
typedef struct Binarrytree {
int data;
struct Binarrytree* lchild;//左孩子结点指针
struct Binarrytree* rchild;//右孩子结点指针
};
3、结构体嵌套
int main() {
//1.定义结构体变量
//直接赋值
struct Student s1 = { "1001",{"旭阳","王"},18,'M' };
printf("%s %s\n", s1.name.firstName, s1.name.lastName);//旭阳 王
//先定义变量,再赋值
struct Student s2;
strcpy(s2.sno,"1002");
strcpy(s2.name.firstName, "longlong");
strcpy(s2.name.lastName, "yu");
s2.age = 18;
s2.gender = 'M';
printf("%s %s %s %d %c\n", s2.sno, s2.name.firstName, s2.name.lastName, s2.age, s2.gender); //1002 longlong yu 18 M
printf("%s %s %s %d %c\n", (&s2)->sno, (&(&s2)->name)->firstName, (&(&s2)->name)->lastName, (&s2)->age, (&s2)->gender); //1002 longlong yu 18 M
//结构体之间用=赋值,相当于做了深拷贝
s1 = s2;//直接赋值
s1.age = 10;
printf("%s %s %s %d %c\n", s1.sno, s1.name.firstName, s1.name.lastName, s1.age, s1.gender);//1002 longlong yu 10 M
printf("%s %s %s %d %c\n", s2.sno, s2.name.firstName, s2.name.lastName, s2.age, s2.gender);//1002 longlong yu 18 M
//数组之间用=赋值,浅拷贝
int arr[3] = { 1,2,3 };
int* ptr = arr;
arr[0] = 100;
printf("%d %d %d\n", arr[0], arr[1], arr[2]);//100 2 3
printf("%d %d %d\n", ptr[0], ptr[1], ptr[2]);//100 2 3
return 0;
}
一、结构体的成员也是变量,那么成员可以是基本数据类型,也可以是数组、指针、结构体类型。如果结构体的成员是另一个结构体,这就构成了结构体嵌套。
二、结构体变量赋值操作
同类型的结构体变量可以使用赋值运算符(=),赋值给另一个变量
这时会生成一个全新副本。系统会分配一块新的内存空间,大小与原来的变量相同,把每个属性都复制过去,即原样生成了一份数据。
结构体变量的传递机制是值传递
验证结构体赋值:值传递、深拷贝
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>struct Car {
char name[20];
double price;
};
int main() {
//验证结构体之间的赋值是传值——深拷贝
struct Car a = { "Audi A6L",390000.88 };
struct Car b = { "BMW X5", 500000.00 };
a = b;
printf("%p %p\n", &a, &b); //地址不同 0000005E84CFF508 0000005E84CFF548
printf("%s %s\n", (&a)->name, (&b)->name);//BMW X5 BMW X5
a.name[0] = 'H';
printf("%s %s\n", (&a)->name, (&b)->name);//HMW X5 BMW X5
return 0;
}