分配结构变量实际上做了什么?

What does assigning a struct's variable actually do?

我正在编写大流行病模拟作为学习 C 语言的一种方式,我正在尝试使用一个名为 Person 的结构将我的所有数据组织在单个项目下。当我尝试检查一个结构的值是否大于 100 然后为另一个属性分配一个值时,我的问题就出现了。

这是我正在处理的结构:

struct Person {
    double levelOfInfection;
    int cleared;
};

这是没有按预期工作的代码。

void checkForClearance(struct Person targetPerson) {
    double val = (double)targetPerson.levelOfInfection - 100.0; // checking if the level of infection is over 100
    printf("%f\n",val); // debug print statement
    if (val >= 0) { // if over 100 set cleared to 1
        targetPerson.cleared = 1;
    } else { // if less that 100 set cleared to 0
        targetPerson.cleared = 0;
    }
}

我的问题是我不明白为结构属性赋值有什么用?因为它似乎不像变量那样工作。如果有人能提供一些关于我写 targetPerson.cleared = 1; 时实际发生的事情的见解,那将有很大帮助。

像这样:

void checkForClearance(struct Person *ptargetPerson) {
    double val = (double)ptargetPerson->levelOfInfection - 100.0; // checking if the level of infection is over 100
    printf("%f\n",val); // debug print statement
    if (val >= 0) { // if over 100 set cleared to 1
        ptargetPerson->cleared = 1;
    } else { // if less that 100 set cleared to 0
        ptargetPerson->cleared = 0;
    }
}

您正在修改结构的副本。你可以通过两种方式做你想做的事:

---

使用指针(注意 -> 运算符而不是 .):

void checkForClearance(struct Person* targetPerson) {
    double val = (double)targetPerson->levelOfInfection - 100.0; // checking if the level of infection is over 100
    printf("%f\n",val); // debug print statement
    if (val >= 0) { // if over 100 set cleared to 1
        targetPerson->cleared = 1;
    } else { // if less that 100 set cleared to 0
        targetPerson->cleared = 0;
    }
}

返回修改后的副本:

struct Person checkForClearance(struct Person targetPerson) {
    double val = (double)targetPerson.levelOfInfection - 100.0; // checking if the level of infection is over 100
    printf("%f\n",val); // debug print statement
    if (val >= 0) { // if over 100 set cleared to 1
        targetPerson.cleared = 1;
    } else { // if less that 100 set cleared to 0
        targetPerson.cleared = 0;
    }
    return targetPerson;
}

请注意,如果您这样做,则需要在调用后重新分配新值:

person = checkForClearance(person);