#include <stdio.h>
// 定义结构体
typedef struct {
int num;
char ch;
} MyStruct;
// 函数声明
void modifyStruct(MyStruct s);
int main() {
MyStruct s = {10, 'A'};
printf("Before modification: num = %d, ch = %c\n", s.num, s.ch);
modifyStruct(s);
printf("After modification: num = %d, ch = %c\n", s.num, s.ch);
return 0;
}
// 函数定义,采用传值方式传递结构体
void modifyStruct(MyStruct s) {
s.num = 20;
s.ch = 'B';
}
输出结果分析
Before modification: num = 10, ch = A
After modification: num = 10, ch = A
- 与预期不一致。预期是修改后
num
为20,ch
为B
,但实际输出还是原来的值。
- 原因:在
modifyStruct
函数中,采用传值方式传递结构体,这意味着函数参数MyStruct s
是主函数中结构体变量s
的一个副本。在函数内部对MyStruct s
的修改,仅仅修改了这个副本的值,而不会影响主函数中原始的结构体变量s
。如果想要修改主函数中结构体变量的值,应该采用传指针方式传递结构体。