C: Passing structure by reference

I defined the following structure:

typedef struct {
    double salary;
} Employee;

I want to change the value salary. I am trying 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, it salaryremains unchanged. What am I doing wrong?

+3
source share
3 answers

You pass 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 a helper variable for some reason:

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

Thus, both variables will point to the same object.

+7
source
void raiseSalary(Employee* e, double newSalary){
    e->salary= newSalary;
    }

, .

+3

, , :

e->salary= newSalary;
+1

All Articles