Here's little code of mine! I'm trying to input values in array of time structure, after input if i call display function in the main(), it will print out garbage values, as we can see the object array is locally binded in the input function. Can anyone tell me how to pass struct with reference of pointer so that the values of the array in the time struct will automatically be updated upon input.
#include <iostream>
usingnamespace std;
int input(struct time);
int output(struct time);
struct time{
int arr[5];
};
int input(struct time x){
for(int i = 0; i<=4; i++){
cin>>x.arr[i];
}
output(x); // works fine for me! but i want to call it in the main function
return 0;
}
int output(struct time x){
for(int i = 0; i<=4; i++){
cout<<x.arr[i];
}
return 0;
}
int main()
{
struct time x;
cout<<"Enter Time for Struct :"<<endl;
input(x);
cout<<endl;
output(x);//it will print garbage values!
return 0;
}
Instead of input(x), try input(&x) to pass a reference to the struct.
No. That passes the address of the struct. To pass by reference the function has to declare that it takes a reference parameter as I showed in my earlier post.