c – 将结构传递给函数

前端之家收集整理的这篇文章主要介绍了c – 将结构传递给函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在练习不同的方法来为结构变量赋值.但当
我试过这个我得到一些垃圾的价值.这是代码. @H_301_3@#include<iostream> using namespace std ; struct Distance{ int feet ; int inches; }; void get_val(Distance ); void disp(Distance); int main(){ Distance l,m ; //Objects get_val(l); get_val(m); disp(l); disp(m); return 0 ; } void get_val(Distance length){ cout<<"\nEnter Length " <<"\nFeet : "; cin>>length.feet; cout<<"\nInches : "; cin>>length.inches; } void disp(Distance length){ cout<<"\nLength : \n" <<"Feet : "<<length.feet <<"\nInches : "<<length.inches ; }

为什么我得到垃圾值作为输出

解决方法

通过参考. @H_301_3@void get_val(Distance&); void get_val(Distance &length){}

您在另一个函数中更改在main函数中创建的结构的值,因此您必须通过引用或使用指针来传递它们.

编辑:

感谢本杰明·林德利

猜你在找的C&C++相关文章