c 语言结构数据作函数变量,C 语言关于结构体做参数传递

首先结构体做函数参数有三种传递方式:

一是传递结构体变量,这是值传递,二是传递结构体指针,这是地址传递,三是传递结构体成员,当然这也分为值传递和地址传递。

以传引用调用方式传递结构比用传值方式传递结构效率高。以传值方式传递结构需要对整个结构做一份拷贝。

下面看一个列子,student结构体中包含该学生的各种信息,我们在change函数中对其进行部分修改,再在主函数中输出其结果

1.下面传递结构体变量

#include

#include

#define format "%d\n%s\n%f\n%f\n%f\n"

struct student

{

int num;

char name[20];

float score[3];

};

void change( struct student stu );

int main()

{

struct student stu;

stu.num = 12345;

strcpy(stu.name, "Tom");

stu.score[0] = 67.5;

stu.score[1] = 89;

stu.score[2] = 78.6;

change(stu);

printf(format, stu.num, stu.name, stu.score[0], stu.score[1],stu.score[2]);

printf("\n");

return 0;

}

void change(struct student stu)

{

stu.score[0] = 100;

strcpy(stu.name, "jerry");

}

8354c497c297d818ec4cce6a78221725.png

可以看到最终输出的值并未改变。。。

2.地址传递

#include

#define format "%d\n%s\n%f\n%f\n%f\n"

struct student

{

int num;

char name[20];

float score[3];

};

void change( struct student* stu );

int main()

{

struct student stu;

stu.num = 12345;

strcpy(stu.name, "Tom");

stu.score[0] = 67.5;

stu.score[1] = 89;

stu.score[2] = 78.6;

change(&stu);

printf(format, stu.num, stu.name, stu.score[0], stu.score[1],stu.score[2]);

printf("\n");

return 0;

}

void change(struct student* p)

{

p->score[0] = 100;

strcpy(p->name, "jerry");

}

ec335d1ba695a90ddc9e33d25d8eac72.png

可以看到,通过地址传递修改了结构体内的数据

用&stu做实参,&stu是结构体变量stu的地址。在调用函数时将该地址传送给形参p(p是指针变量)。这样p就指向stu。

在change函数中改变结构体内成员的值,在主函数中就输出了改变后的值

3.结构体成员的地址传递和值传递

这个类似于单一变量的传递,这里也没必要说了,当然是地址传递才能修改。

把一个完整的结构体变量作为参数传递,要将全部成员值一个一个传递,费时间又费空间,开销大。如果结构体类型中的成员很多,或有一些成员是数组,则程序运行效率会大大降低。在这种情况下,用指针做函数参数比较好,能提高运行效率。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值