How to pass a struct member as a pointer in a function?

Inside the function clear_sensors_struc, it is indeed correct to do:

//this way compiles fine, but i don´t think it´s correct
clearCircularBuffer(&(sensors_struct->st_circular_buffer));

It's right because (inside function clear_sensors_struc):

  • sensors_struct: is a pointer to a struct.
  • sensors_struct->st_circular_buffer: dereferences sensors_struct (using ->) and allows you to access its member st_circular_buffer.
  • &(sensors_struct->st_circular_buffer): is a pointer to the member st_circular_buffer of struct sensors_struct that happens to be a struct struct_circ_buff.

As the function clearCircularBuffer requires a pointer, it will compile and work right.

Regarding the function to clean the array of structs, what about this?:

void clear_sensors_struc_array(struct_sens *sensors_struct)
{
    int i=0;    

    for(i=0;i<MAX_NUMBER_OF_SENSORS;i++)
    {         
        clear_sensors_struc((sensors_struct+i));
    }
}

Per Nicolás' example:

clearCircularBuffer(&(sensors_struct->st_circular_buffer));

We can directly use

clearCircularBuffer(&sensors_struct->st_circular_buffer);

Because -> gets precedence over &.

Tags:

C