C 言語で 2 つの構造体を交換の方法
C言語では一時変数を使って構造体の値を入れ替えることができます。
以下にコードの例を示します。
#include<stdio.h>
#include<string.h>
// 定义结构体
struct Student {
char name[20];
int age;
};
void swap(struct Student *s1, struct Student *s2) {
struct Student temp; // 临时变量
temp = *s1; // 将s1的值拷贝给temp
*s1 = *s2; // 将s2的值拷贝给s1
*s2 = temp; // 将temp的值拷贝给s2
}
int main() {
struct Student s1, s2;
// 初始化s1的值
strcpy(s1.name, "John");
s1.age = 20;
// 初始化s2的值
strcpy(s2.name, "Alice");
s2.age = 25;
printf("交换前的值:\n");
printf("s1:name = %s, age = %d\n", s1.name, s1.age);
printf("s2:name = %s, age = %d\n", s2.name, s2.age);
// 调用swap函数交换s1和s2的值
swap(&s1, &s2);
printf("交换后的值:\n");
printf("s1:name = %s, age = %d\n", s1.name, s1.age);
printf("s2:name = %s, age = %d\n", s2.name, s2.age);
return 0;
}
上述のコードでは、Student構造体という構造体を定義し、その構造体の値を入れ替えるswap関数という関数を宣言しています。 main関数で構造体の値を初期化し、swap関数で値を入れ替えて、最後に入れ替え後の結果を出力しています。
出力は次のとおりです。
交换前的值:
s1:name = John, age = 20
s2:name = Alice, age = 25
交换后的值:
s1:name = Alice, age = 25
s2:name = John, age = 20