How to Pass Struct in Function as Reference or Pointer?

Apr 15, 2014 at 3:38pm
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

#include <iostream>
using namespace 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;
}
Last edited on Apr 15, 2014 at 3:38pm
Apr 15, 2014 at 3:43pm
line 12: You're passing x by value, not by reference. Therefore any changes to x are local and are not passed back to the caller.

Passing by reference:
 
int input(struct time &x)


Apr 15, 2014 at 4:37pm
Is there a c++ compiler that requires giving type struct? struct time x;
Apr 16, 2014 at 9:38am
This code works fine in Code::blocks but in Visual Studio it gives

error C4700: uninitialized local variable 'x' used

Why is that?
Last edited on Apr 16, 2014 at 9:39am
Apr 16, 2014 at 9:53am
closed account (2UD8vCM9)
1
2
3
4
5
6
7
8
9
10
int main()
{
    struct time x;
    cout<<"Enter Time for Struct :"<<endl;
    input(x);
    cout<<endl;

    output(x);//it will print garbage values!
    return 0;
}


It's not struct time x;
it's time x;

Instead of input(x), try input(&x) to pass a reference to the struct.
Apr 16, 2014 at 1:08pm
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.


Topic archived. No new replies allowed.