0

I have nested structs and I'm having trouble assigning values to the inner struct in different functions. My structs are defined as:

typedef struct {
    double reading;
    float readingTime;
    int readingNum;
} Measurement;

typedef struct {
    Measurement vref;
    Measurement vout;
    Measurement voutShort; 
} Unit;

In the function (measureUnit()) where I declare Unit unit;I call takeMeasurement(unit) (which I simplified for clarity below) and where I try to assign values to some values in the inner Measurement struct :

takeMeasurement(Unit unit){
    int readingNum = 42;
    unit.vout.readingNum = readingNum;
}

When I then try to access these values in printData(Unit unit) which is called from measureUnit(),

`printf("%i", unit.vout.readingNum)`

always prints 0.

Shouldn't these values "follow" unit around through different functions?

2 Answers 2

5

C passes arguments by value resulting in the changes being made to unit in takeMeasurement() being applied to a copy of the argument supplied to the function. Pass the address of a Unit to the function to ensure changes are visible to the caller:

void takeMeasurement(Unit* unit){
    int readingNum = 42;
    unit->vout.readingNum = readingNum;
}

To invoke:

Unit u = { 0.0 };
takeMeasurement(&u);

It is also desirable to pass a pointer to a const struct to a function that only reads the values of the struct to avoid making a copy of the struct, particularly if the struct is large:

void printData(const Unit* unit)
{
    printf("%i", unit->vout.readingNum);
}
Sign up to request clarification or add additional context in comments.

Comments

2

You pass the struct itself to the function, which means you pass a copy of your struct to the function and modify this copy, not the original structure. You might want to pass a pointer to the struct instead:

takeMeasurement(Unit* unit){
    int readingNum = 42;
    unit->vout.readingNum = readingNum;
}

// call it something like that
takeMeasurement(&my_unit_struct);
//              ^ this means "the address of my_unit_struct"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.