Home > front end >  Pass nested struct to a function
Pass nested struct to a function

Time:10-28

Hello I have the following code:

struct temperatures_t {
  char lowTempSetting = 18;
  char highTempSetting = 26;
  char currentTemp = 23;
};

struct runningState_t {
  struct temperatures_t temperatures;
};

struct runningState_t runningState;

void test(runningState_t *runningStateVar) {
  runningStateVar->temperatures->lowTempSetting  ;
  runningStateVar->temperatures->currentTemp = 10;
  printf(runningStateVar.temperatures.lowTempSetting);
}

void main() {
  test(&runningState);
}

But getting the following error on the runningState->temperatures-> lines:

{
"message": "operator -> or ->* applied to \"temperatures_t\" instead of to a pointer type"
}

I have also tried variations:

  &(runningState)->temperatures->lowTempSetting  ;

And other variations based off what I saw in this answer: C pass a nested structure within a structure to a function?

But without much luck

CodePudding user response:

In test, the local argument variable runningState (not to be confused with the global variable of the same name) is a pointer to a structure object, so the arrow operator -> is the correct to use to access its members.

But runningState->temperatures is not a pointer, it's an actual structure object. Therefore you must use the dot . to access its members:

runningState->temperatures.lowTempSetting  ;
//                        ^
//      Note using dot here
  • Related