用c语言指针实现一个结构体数组对另一个结构体数组的赋值
时间: 2023-12-18 12:29:07 浏览: 231
以下是用C语言指针实现一个结构体数组对另一个结构体数组的赋值的示例代码:
```c
#include <stdio.h>
#include <string.h>
struct student {
int num;
char name[10];
char sex;
double height;};
int main() {
struct student stus1[3] = {{1001, "Tom", 'M', 1.75}, {1002, "Jerry", 'F', 1.65}, {1003, "Mike", 'M', 1.80}};
struct student stus2[3];
struct student *p1, *p2;
p1 = stus1;
p2 = stus2;
memcpy(p2, p1, sizeof(stus1));
for (int i = 0; i < 3; i++) {
printf("stus2[%d]: num=%d, name=%s, sex=%c, height=%.2f\n", i, (p2+i)->num, (p2+i)->name, (p2+i)->sex, (p2+i)->height);
}
return 0;
}
```
解释如下:
1. 定义了一个结构体`student`,包含学号、姓名、性别和身高四个成员变量。
2. 定义了两个结构体数组`stus1`和`stus2`,分别用于存储学生信息。
3. 定义了两个指向结构体的指针`p1`和`p2`,并将`p1`指向`stus1`数组的首元素,将`p2`指向`stus2`数组的首元素。
4. 使用`memcpy`函数将`stus1`数组中的数据复制到`stus2`数组中。
5. 使用指针遍历`stus2`数组,并输出每个学生的信息。
阅读全文
相关推荐


















