Nakib
Nakib

Reputation: 4713

Unexpected result while passing struct to a function

I want to pass a struct to function something like below (I know i can pass single member to function like input(int age, string s) but i want to pass whole struct like input(student s) )

#include <iostream>

using namespace std;

struct student
{
    string name;
    int age;
};

void input(student s)
{
    cout << "Enter Name: ";
    cin >> s.name;

    cout << "Enter age: ";
    cin >> s.age;
}

int main(int argc, char *argv[]) {
    struct student s1;

    input(s1);

    cout << "Name is: " << s1.name << endl;
    cout << "Age is: " << s1.age << endl;

}

Above code does not produce correct output, I want to use above code with pointer so to get expected output.

Test:If i input name to "abc" and age to 10. It does not get printed in main

Upvotes: 1

Views: 100

Answers (3)

juanchopanza
juanchopanza

Reputation: 227608

Your function makes a local copy of the input. It looks like you need to pass by reference:

void input(student& s) { .... }
//                ^

By default, function arguments are passed by value, so this issue is not specific to classes. For example,

void increment_not(int i) { ++i; }

int i = 41;
increment_not(i);
std::cout << i << std::endl; // prints 41

Upvotes: 5

shofee
shofee

Reputation: 2129

You need to pass the struct by reference, rite now you are passing it by copy so whatever changes are made they are on copy of the passed object.

void input(student& s){....}

Upvotes: 0

Yu Hao
Yu Hao

Reputation: 122493

Your function passes student s by value, that's why the variable s1 in main doesn't change.

Change it to pass reference:

void input(student& s)
//                ^

Upvotes: 1

Related Questions