c语言对结构体赋值
时间: 2023-07-09 18:14:25 浏览: 115
c语言结构体
C语言中可以通过以下方式对结构体进行赋值:
1. 逐个成员赋值
```c
struct student {
char name[20];
int age;
float score;
};
struct student s = {"Tom", 18, 90.5}; // 定义并初始化结构体
s.name = "Jerry"; // 错误,不能直接赋值字符串
strcpy(s.name, "Jerry"); // 正确,使用strcpy函数赋值字符串
s.age = 19;
s.score = 85.6;
```
2. 整体赋值
```c
struct student s1 = {"Tom", 18, 90.5};
struct student s2;
s2 = s1; // 整体赋值,s2的每个成员和s1相同
```
3. 使用指针
```c
struct student s1 = {"Tom", 18, 90.5};
struct student *ps;
ps = &s1;
(*ps).age = 19; // 使用指针访问结构体成员
ps->score = 85.6; // 等价于(*ps).score = 85.6;
```
阅读全文