4.1 C/C++ 使用结构与指针

C/C++语言是一种通用的编程语言,具有高效、灵活和可移植等特点。C语言主要用于系统编程,如操作系统、编译器、数据库等;C语言是C语言的扩展,增加了面向对象编程的特性,适用于大型软件系统、图形用户界面、嵌入式系统等。C/C++语言具有很高的效率和控制能力,但也需要开发人员自行管理内存等底层资源,对于初学者来说可能会有一定的难度。

结构体的定义与使用: 结构体的引用需要注意,当引用普通结构体时使用点即可,但如果引用指针则需要使用箭头取地址.

#include <stdio.h>
#include <stdlib.h>

struct Student
{
int num;
char name[30];
char age;
};

int main(int argc, char* argv[])
{
struct Student stu = { 1001, "lyshark", 22 };
printf("普通引用: %d --> %s \n", stu.num, stu.name);

struct Student *ptr; // 定义结构指针
ptr = &stu; // 指针的赋值
printf("指针引用: %d --> %s \n", ptr->num, ptr->name);

system("pause");
return 0;
}

动态分配结构体成员: 分配结构体成员也有两种方式,第一种是直接分配整个结构体空间,第二种则是单独分配结构体成员.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
struct Student
{
char name[30];
char age;
};
struct Person
{
char *name;
int age;
}person;

// 直接分配整个结构体空间大小
struct Student *stu = malloc(sizeof(struct Student));
stu->age = 24;
strcpy(stu->name, "lyshark");
printf("姓名: %s 年龄: %d \n", stu->name, stu->age);

// ----------------------------------------------------------
struct Person *ptr = &person;
// 第二种则是单独为该结构体中的某个成员分配空间
ptr->name = (char *)malloc(sizeof(char)* 20);
strcpy(ptr->name, "lyshark");
ptr->age = 23;

printf("姓名: %s 年龄: %d \n", ptr->name, ptr->age);
free(ptr->name);

system("pause");
return 0;
}

结构体变量数组: 结构体也可以分配成数组的形式,如下则是对该数组的分配与遍历过程.

#include <stdio.h>
#include <stdlib.h>

typedef struct Student
{
int uid;
char name[64];
}Student;

void Print(struct Student *ptr, int len)
{
for (int x = 0; x < len; x++)
{
printf("ID: %d ---> Name: %s \n", ptr[x].uid,ptr[x].name);
}
}

int main(int argc, char* argv[])
{
// 第一种: 栈上分配结构体(聚合初始化)
struct Student stu1[] = {
{ 1, "admin" },
{ 2, "guest" },
{ 3, "root" },
};

int len = sizeof(stu1) / sizeof(struct Student);
Print(stu1, len);

// 第二种: 在堆上分配空间.
struct Student *stu2 = malloc(sizeof(struct Student) * 5);
// 通过循环拷贝数据
for (int x = 0; x < 5; x++)
{
stu2[x].uid = x;
strcpy(stu2[x].name, "lyshark");
}
Print(stu2, 5);

system("pause");
return 0;
}

结构体内存深拷贝: 结构体的拷贝可以使用p1=p2这种形式属于浅层拷贝,如果需要深层拷贝则需要使用如下拷贝方式.

#include <stdio.h>
#include <stdlib.h>

typedef struct Person
{
int uid;
char *name;
}Person;

int main(int argc, char* argv[])
{
struct Person p1, p2,p3;

p1.name = malloc(sizeof(char)* 64);
strcpy(p1.name, "admin");
p1.uid = 1;

p2.name = malloc(sizeof(char)* 64);
strcpy(p2.name, "guest");
p2.uid = 2;

// 内存深拷贝: 将 p2.name --> 拷贝到 p1.name
if (p1.name != NULL)
{ // 首先释放p1.name的内存空间
free(p1.name);
p1.name == NULL;
}
p1.name = malloc(strlen(p2.name) + 1); // 重新为p1分配内存
strcpy(p1.name, p2.name); // 直接拷贝数据
p2.uid = p1.uid;
printf("p1 拷贝到p2 --> %s \n", p2.name);

// 内存深拷贝: 使用 p2.name --> 赋值到 p3.name
p3.name = malloc(strlen(p2.name) + 1); // 分批空间
strcpy(p3.name, p2.name); // 直接拷贝
p3.uid = 3;
printf("p2 拷贝到 p3 --> %s \n", p3.name);

system("pause");
return 0;
}

结构体偏移量计算: 通过使用offsetof()宏函数,我们就可以实现计算出结构中指定成员之间的偏移值了.

#include <stdio.h>
#include <stddef.h>

int main(int argc, char* argv[])
{
// 第一种方式: 单独的结构体中,计算结构之间的大小间隔
struct Student { int uid; char *name; }; // 定义Student结构体
struct Student stu = { 1, "lyshark" }; // 为结构体实例化,并赋值

int *struct_offset = (int *)((char *)&stu);

printf("Student 结构的首地址(基址): %x \n", struct_offset);

// offsetof( struct Student,name) --> 取出Student里面的name的偏移
int *offset = (int *)((char *)&stu + offsetof(struct Student, name));
printf("Student 结构里面name成员的地址: %x \n", offset);

int between_offset = (int)offset - (int)struct_offset;
printf("name成员与Student基址之间的偏移: %d \n\n\n", between_offset);

// --------------------------------------------------------------------
// 第二种方式: 在嵌套结构体中取地址,计算偏移
struct SuperClass
{
int uid;
char *name;
struct StuClass
{
int s_id;
char *s_name;
}stu;
};

// 首先先来初始化,这里可以连在一起写的
struct SuperClass super = { 0, "admin", 1001, "lyshark" };

int stu_class_offset = offsetof(struct SuperClass, stu); // 定位StuClass的基址
int stu_sid_offset = offsetof(struct StuClass, s_id); // 找到第一个s_id的基址

// SuperClass(基址) + StuClass(偏移) + s_id(偏移) 找到s_id首地址
int s_id_offset = ((char *)&super + stu_class_offset) + stu_sid_offset;
printf("s_id 首地址: %x --> 验证地址: %x \n", s_id_offset, &super.stu.s_id);

// 解析 s_id 里面的数值
int s_id_value = *(int *)((char *)&super + stu_class_offset) + stu_sid_offset;
printf("s_id 里面的值为: %d \n", s_id_value);

// 另一种解析 s_name 里面的数值
int s_name_value = ((struct StuClass*)((char *)&super + stu_class_offset))->s_name;
printf("s_name 里面的值为: %s \n", s_name_value);

system("pause");
return 0;
}

实现结构体字段排序: 首先对比结构中的UID,通过冒泡排序将UID从小到大排列,也可以通过Name字段进行排序.

#include <stdio.h>
#include <stdlib.h>

struct Student
{
int uid;
char name[32];
double score;
};

int StructSort(struct Student *stu,int len)
{
for (int x = 0; x < len - 1; x++)
{
for (int y = 0; y < len - x - 1; y++)
{
// if (strcmp(stu[y].name, stu[y + 1].name) > 0)
if (stu[y].uid > stu[y + 1].uid)
{
// 结构体变量互换,将用户UID从小到大排列
struct Student tmp = stu[y];
stu[y] = stu[y + 1];
stu[y+1] = tmp;
}
}
}
return 0;
}

void MyPrint(struct Student *stu,int len)
{
for (int x = 0; x < len; x++)
printf("Uid: %d Name: %s Score: %.1f \n", stu[x].uid,stu[x].name,stu[x].score);
}

int main(int argc, char* argv[])
{
struct Student stu[3] = {
{8,"admin",79.5},
{5,"guest",89.5},
{1,"root",99},
};

StructSort(stu, 3); // 调用排序
MyPrint(stu, 3); // 输出结果

system("pause");
return 0;
}

结构体数据之间的交换: 将两个结构体内的数据进行数据交换,类似于反转.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Student
{
char *name;
int score[3];
};

int StructExchange(struct Student *stu, int len, char *str1,char *str2)
{
struct Student *ptr1;
struct Student *ptr2;

// 找到两个名字所对应的成绩
for (int x = 0; x < len; ++x)
{
if (!strcmp(stu[x].name, str1))
ptr1 = &stu[x];
if (!strcmp(stu[x].name, str2))
ptr2 = &stu[x];
}

// 开始交换两个人的成绩
for (int y = 0; y < 3; y++)
{
int tmp = ptr1->score[y];
ptr1->score[y] = ptr2->score[y];
ptr2->score[y] = tmp;
}
return 0;
}

void MyPrint(struct Student *stu,int len)
{
for (int x = 0; x < len; x++)
{
printf("Name: %s --> score: %d %d %d \n", stu[x].name, stu[x].score[0], stu[x].score[1], stu[x].score[2]);
}
}

int main(int argc, char* argv[])
{
struct Student stu[3];

// 动态开辟空间,并动态输入姓名与成绩
// admin 1 1 1 / guest 2 2 2 / root 3 3 3
for (int x = 0; x < 3; x++)
{
stu[x].name = (char *)malloc(sizeof(char) * 64); // 开辟空间
scanf("%s%d%d%d", stu[x].name, &stu[x].score[0], &stu[x].score[1], &stu[x].score[2]);
}

MyPrint(&stu, 3);
// 开始交换root->admin 两个人的成绩
StructExchange(&stu, 3, "root", "admin");
printf("----------------------------\n");
MyPrint(&stu, 3);

// 动态内存的释放
for (int y = 0; y < 3; y++)
free(stu[y].name);

system("pause");
return 0;
}

结构体嵌套一级指针: 首先开辟3个指针变量,然后分别开辟这些存储空间,并赋值,最后打印出来.

#include <stdio.h>
#include <stdlib.h>

typedef struct Person
{
int id;
char *name;
int age;
}Person;

// 分配内存空间,每一个二级指针中存放一个一级指针
struct Person ** allocateSpace()
{
// 分配3个一级指针,每一个指针指向一个结构首地址
struct Person **tmp = malloc(sizeof(struct Person *) * 3);
for (int x = 0; x < 3; x++)
{
tmp[x] = malloc(sizeof(struct Person)); // (真正的)分配一个存储空间
tmp[x]->name = malloc(sizeof(char)* 64); // 分配存储name的空间
sprintf(tmp[x]->name, "name_%d", x); // 自动的输入一个数据
tmp[x]->id = x; // 填充剩余的元素
tmp[x]->age = x + 10;
}
return tmp; // 最后返回一个二级指针
}

// 循环输出数据
void MyPrint(struct Person **person)
{
for (int x = 0; x < 3; x++)
printf("Name: %s \n", person[x]->name);
}

// 释放内存空间,从后向前,从小到大释放
void freeSpace(struct Person **person)
{
if (person != NULL)
{
for (int x = 0; x < 3; x++)
{
if (person[x]->name != NULL)
{
printf("%s 内存被释放 \n", person[x]->name);
free(person[x]->name);
person[x]->name = NULL;
}
free(person[x]);
person[x] = NULL;
}
free(person);
person = NULL;
}
}

int main(int argc, char* argv[])
{
struct Person **person = NULL;

person = allocateSpace();
MyPrint(person);
freeSpace(person);

system("pause");
return 0;
}

结构体嵌套二级指针: 结构体内嵌套二级指针,后弦分配二级指针,接着在二级指针中继续分配一级指针.

#include <stdio.h>
#include <stdlib.h>

struct Student
{
char * name;
}Student;

struct Teacher
{
char *name;
char **student;
}Teacher;

void allocateSpace(struct Teacher ***ptr)
{
// 首先分配三个二级指针,分别指向三个老师的结构首地址(此处并未赋值,只是一个指针)
struct Teacher **teacher_ptr = malloc(sizeof(struct Teacher *) * 3);

for (int x = 0; x < 3; x++)
{
// 先来分配老师姓名存储字符串,然后依次循环赋予一个初始值
teacher_ptr[x] = malloc(sizeof(struct Teacher)); // 给teacher_ptr整体分配空间
teacher_ptr[x]->name = malloc(sizeof(char)* 64); // 给teacher_ptr里面的name分配空间
sprintf(teacher_ptr[x]->name, "teacher_%d", x); // 分配好空间之后,将数据拷贝到name里面

// -------------------------------------------------------------------------------------
// 接着分配该老师管理的学生数据,此处默认每个老师管理四个学生
teacher_ptr[x]->student = malloc(sizeof(char *) * 4); // 给teacher_ptr里面的student分配指针
for (int y = 0; y < 4; y++)
{
teacher_ptr[x]->student[y] = malloc(sizeof(char) * 64); // 此处开始为学生姓名分配空间
sprintf(teacher_ptr[x]->student[y], "%s_stu_%d", teacher_ptr[x]->name, y);
}
}
// 最后将结果通过指针的方式,传递出去.
*ptr = teacher_ptr;
}

// 输出老师和学生数据
void MyPrint(struct Teacher **ptr)
{
for (int x = 0; x < 3; x++)
{
printf("老师姓名: %s \n", ptr[x]->name);
for (int y = 0; y < 4; y++)
{
printf("--> 学生: %s \n", ptr[x]->student[y]);
}
}
}

// 最后释放内存
void freeSpace(struct Teacher **ptr)
{
for (int x = 0; x < 3; x++)
{
if (ptr[x]->name != NULL)
{
free(ptr[x]->name);
ptr[x]->name = NULL;
}

for (int y = 0; y < 4; y++)
{
if (ptr[x]->student[y] != NULL)
{
free(ptr[x]->student[y]);
ptr[x]->student[y] = NULL;
}
}
free(ptr[x]->student);
ptr[x]->student = NULL;
}
}

int main(int argc, char* argv[])
{
struct Teacher **teacher_ptr = NULL;

allocateSpace(&teacher_ptr);
MyPrint(teacher_ptr);
freeSpace(teacher_ptr);

system("pause");
return 0;
}

结构体内嵌共用体: 结构体内嵌套共用体,首先新增结构体Person该结构内判断是学生则解析课程,是老师则解析班级.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

struct Person
{
int uid; // 编号
char name[20]; // 姓名
char jobs; // 老师=t 或 学生 = s
union
{
char stu_class[32]; // 学生所在班级
char tea_class[32]; // 老师的所教课程
}category;
};

int main(int argc, char* argv[])
{
struct Person person[3];

for (int x = 0; x < 3; x++)
{
// 首先输入前三项,因为这三个数据是通用的,老师学生都存在的属性
printf("输入: ID 姓名 工作类型(s/t) \n");
scanf("%d %s %c", &person[x].uid, &person[x].name, &person[x].jobs);

if (person[x].jobs == 's') // 如果是学生,输入stu_class
scanf("%s", person[x].category.stu_class);
if (person[x].jobs == 't') // 如果是老师,输入tea_class
scanf("%s", person[x].category.tea_class);
}

printf("--------------------------------------------------------------\n");

for (int y = 0; y < 3; y++)
{
if (person[y].jobs == 's')
printf("老师: %s 职务: %s \n", person[y].name, person[y].category.tea_class);
if (person[y].jobs == 't')
printf("学生: %s 班级: %s \n", person[y].name, person[y].category.stu_class);
}
system("pause");
return 0;
}