Home > Net >  What does assigning a struct's variable actually do?
What does assigning a struct's variable actually do?

Time:12-17

I'm writing a pandemic simulation as a way of learning C and I'm trying to use a struct called Person to organize all of my data under single items. My issue arises when I try to check if one of the struct's values is greater than 100 and then assign another attribute a value.

This is the struct I'm working off of:

struct Person {
    double levelOfInfection;
    int cleared;
};

This is the code that isn't working as intended.

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;
    }
}

My question is that I don't understand what assigning a value to a struct attribute does? Since it doesn't seem to work as a variable does. If someone could provide some insight on what is actually happening when I write targetPerson.cleared = 1; that would be of great help.

CodePudding user response:

You are modifying the copy of the struct. You can do what you want in two ways:

---

Using pointers (note the -> operator instead of .):

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;
    }
}

Returning the modified copy:

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;
}

note that if you are doing it this way then you need to reassign the new value after calling:

person = checkForClearance(person);

CodePudding user response:

something like this:

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;
    }
}
  • Related