简体   繁体   English

C:通过引用传递struct

[英]C: Passing struct by reference

I've defined the following struct: 我已经定义了以下结构:

typedef struct {
    double salary;
} Employee;

I want to change the value of salary . 我想改变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. 当我调用此函数时, salary保持不变。 What am I doing wrong? 我究竟做错了什么?

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. 这样,两个变量都将指向同一个对象。

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

In your code you create a local copy of the struct and only this local copy is changed. 在代码中,您将创建结构的本地副本,并且仅更改此本地副本。

假设你已经在调用者处分配了内存,它应该是:

e->salary= newSalary;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM