用c语言写一swap函数,用于接收两个结构体指针,然后交换结构体内三个元素,包含姓名,国家,成绩
时间: 2024-02-07 18:03:52 浏览: 28
好的,下面是一个用C语言编写的swap函数,用于交换两个结构体指针中的三个元素:
```c
#include <stdio.h>
#include <string.h>
// 定义一个结构体
struct student {
char name[20];
char country[20];
int score;
};
// 定义一个swap函数
void swap(struct student *p1, struct student *p2){
struct student tmp;
// 交换姓名
strcpy(tmp.name, p1->name);
strcpy(p1->name, p2->name);
strcpy(p2->name, tmp.name);
// 交换国家
strcpy(tmp.country, p1->country);
strcpy(p1->country, p2->country);
strcpy(p2->country, tmp.country);
// 交换成绩
tmp.score = p1->score;
p1->score = p2->score;
p2->score = tmp.score;
}
int main(){
// 定义两个结构体指针
struct student *p1, *p2;
// 分配内存
p1 = (struct student*)malloc(sizeof(struct student));
p2 = (struct student*)malloc(sizeof(struct student));
// 初始化
strcpy(p1->name, "Tom");
strcpy(p1->country, "USA");
p1->score = 90;
strcpy(p2->name, "Tony");
strcpy(p2->country, "Canada");
p2->score = 80;
// 打印交换前的值
printf("Before Swap:\n");
printf("p1: name=%s, country=%s, score=%d\n", p1->name, p1->country, p1->score);
printf("p2: name=%s, country=%s, score=%d\n", p2->name, p2->country, p2->score);
// 调用swap函数进行交换
swap(p1, p2);
// 打印交换后的值
printf("After Swap:\n");
printf("p1: name=%s, country=%s, score=%d\n", p1->name, p1->country, p1->score);
printf("p2: name=%s, country=%s, score=%d\n", p2->name, p2->country, p2->score);
// 释放内存
free(p1);
free(p2);
return 0;
}
```
这个swap函数接收两个结构体指针p1和p2,然后使用一个临时结构体tmp来存储p1和p2的值,然后交换结构体中的三个元素:姓名,国家和成绩。最后打印交换前和交换后的值,并释放内存。