最新消息: USBMI致力于为网友们分享Windows、安卓、IOS等主流手机系统相关的资讯以及评测、同时提供相关教程、应用、软件下载等服务。

c语言结构体整体交换

IT圈 admin 55浏览 0评论

2024年3月31日发(作者:国英发)

在C语言中,可以使用结构体变量整体交换的方法,即将两个结

构体变量的所有成员逐个交换。以下是一个示例代码:

```c

#include

#include

struct Student {

char name[20];

int age;

float score;

};

void swap(struct Student *a, struct Student *b) {

struct Student temp = *a;

*a = *b;

*b = temp;

}

int main() {

struct Student stu1 = {"Tom", 18, 80.0};

struct Student stu2 = {"Jerry", 20, 90.0};

printf("Before swap:n");

printf(": %s, : %d, : %.1fn",

, , );

printf(": %s, : %d, : %.1fn",

, , );

swap(&stu1, &stu2);

printf("After swap:n");

printf(": %s, : %d, : %.1fn",

, , );

printf(": %s, : %d, : %.1fn",

, , );

return 0;

}

```

在上述代码中,我们定义了一个结构体`Student`,包含三个成员

变量`name`、`age`和`score`。我们还定义了一个函数`swap()`,用于交

换两个`Student`结构体变量的所有成员。该函数接受两个指向

`Student`结构体的指针作为参数,将第一个结构体的所有成员复制到

临时变量中,然后将第二个结构体的所有成员复制到第一个结构体中,

最后将临时变量的所有成员复制到第二个结构体中。这样就完成了两

个结构体变量的整体交换。在`main()`函数中,我们定义了两个

`Student`结构体变量`stu1`和`stu2`,并初始化了它们的值。然后调用

`swap()`函数交换这两个结构体变量的所有成员,并输出交换前后的

值。

2024年3月31日发(作者:国英发)

在C语言中,可以使用结构体变量整体交换的方法,即将两个结

构体变量的所有成员逐个交换。以下是一个示例代码:

```c

#include

#include

struct Student {

char name[20];

int age;

float score;

};

void swap(struct Student *a, struct Student *b) {

struct Student temp = *a;

*a = *b;

*b = temp;

}

int main() {

struct Student stu1 = {"Tom", 18, 80.0};

struct Student stu2 = {"Jerry", 20, 90.0};

printf("Before swap:n");

printf(": %s, : %d, : %.1fn",

, , );

printf(": %s, : %d, : %.1fn",

, , );

swap(&stu1, &stu2);

printf("After swap:n");

printf(": %s, : %d, : %.1fn",

, , );

printf(": %s, : %d, : %.1fn",

, , );

return 0;

}

```

在上述代码中,我们定义了一个结构体`Student`,包含三个成员

变量`name`、`age`和`score`。我们还定义了一个函数`swap()`,用于交

换两个`Student`结构体变量的所有成员。该函数接受两个指向

`Student`结构体的指针作为参数,将第一个结构体的所有成员复制到

临时变量中,然后将第二个结构体的所有成员复制到第一个结构体中,

最后将临时变量的所有成员复制到第二个结构体中。这样就完成了两

个结构体变量的整体交换。在`main()`函数中,我们定义了两个

`Student`结构体变量`stu1`和`stu2`,并初始化了它们的值。然后调用

`swap()`函数交换这两个结构体变量的所有成员,并输出交换前后的

值。

发布评论

评论列表 (0)

  1. 暂无评论