一个结构体数组的一部分对另一个结构体数组的赋值
时间: 2023-12-18 21:29:09 浏览: 154
结构体中数组成员赋值
5星 · 资源好评率100%
假设我们有两个结构体数组team1和team2,它们的结构体模板都是Player,现在要将team1中的前三个元素的值赋给team2中的后三个元素,可以使用循环遍历实现:
```c
#include <stdio.h>
#include <string.h>
struct Player {
char name[32];
char sex[32];
char position[32];
float height;
float weight;
};
int main() {
struct Player team1[6] = {
{"player1", "male", "forward", 180, 70},
{"player2", "female", "guard", 170, 60},
{"player3", "male", "center", 190, 80},
{"player4", "female", "forward", 175, 65},
{"player5", "male", "guard", 185, 75},
{"player6", "female", "center", 180, 70}
};
struct Player team2[6];
// 将team1中的前三个元素的值赋给team2中的后三个元素
for (int i = 0; i < 3; i++) {
strcpy(team2[i+3].name, team1[i].name);
strcpy(team2[i+3].sex, team1[i].sex);
strcpy(team2[i+3].position, team1[i].position);
team2[i+3].height = team1[i].height;
team2[i+3].weight = team1[i].weight;
}
// 输出team2中的元素
for (int i = 0; i < 6; i++) {
printf("name: %s, sex: %s, position: %s, height: %.2f, weight: %.2f\n", team2[i].name, team2[i].sex, team2[i].position, team2[i].height, team2[i].weight);
}
return 0;
}
```
输出结果为:
```
name: , sex: , position: , height: 0.00, weight: 0.00
name: , sex: , position: , height: 0.00, weight: 0.00
name: , sex: , position: , height: 0.00, weight: 0.00
name: player1, sex: male, position: forward, height: 180.00, weight: 70.00
name: player2, sex: female, position: guard, height: 170.00, weight: 60.00
name: player3, sex: male, position: center, height: 190.00, weight: 80.00
```
阅读全文