Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Passing struct by reference

Tags:

c

reference

I've defined the following struct:

typedef struct {
    double salary;
} Employee;

I want to change the value of salary. I attempt to pass it by reference, but the value remains unchanged. Below is the code:

void raiseSalary (Employee* e, double newSalary) {
    Employee myEmployee = *e;
    myEmployee.salary = newSalary;
}

When I call this function, the salary remains unchanged. What am I doing wrong?

like image 336
AFS Avatar asked Jun 08 '26 00:06

AFS


1 Answers

You're passing a pointer to the original, but then you create a copy of it:

Employee myEmployee =*e;

creates a copy.

e->salary = newSalary;

will do it. Or, if you must have an auxiliary variable for whatever reasons:

Employee* myEmployee =e;
Myemployee->salary= newSalary;

This way, both variables will point to the same object.

like image 148
Luchian Grigore Avatar answered Jun 10 '26 17:06

Luchian Grigore