I am trying to access a pointer index value from an array of structure pointers:
typedef struct
{
bool status;
uint8_t sensnr;
uint8_t set_vallue;
uint8_t actuval_value;
} temp_t;
//array of struct
temp_t temp[5];
typedef struct
{
uint8_t senspwrsource;
uint8_t sensnr;
uint8_t max_value;
} sensor_t;
//array of structs
sensor_t sens[5];
typedef union {
temp_t temp;
sensor_t sensor;
} temp_sens_t;
typedef struct
{
bool status;
struct temp_sens_t *temp_value[3];
struct temp_sens_t *sensors[3];
char sensor_name[MAX_LEN];
} tempsensors_t;
//array of structures
tempsensors_t sensors[5];
I am able to assign all values but I am not able to read values from struct pointer "temp_value[3]".
So far I have tried like this:
temp_t *tempinfo;
tempinfo = &sensors[1]->temp_value[0];
//trying to access values like this but not working.
teminfo.sensnr ;
How do I access values from an array of struct pointers with index [0 to 2]?
You have (in part):
typedef union {
temp_t temp;
sensor_t sensor;
} temp_sens_t;
typedef struct
{
bool status;
struct temp_sens_t *temp_value[3];
struct temp_sens_t *sensors[3];
char sensor_name[MAX_LEN];
} tempsensors_t;
That doesn't mean what you think it means, though. None of your defined structures or unions has a tag (as in struct tag { … }
). You define a type named temp_sens_t
, but you do not define a type struct temp_sens_t
(and even if you did, it would be unrelated to the type known as temp_sens_t
— structure tags are in a different namespace from 'ordinary identifiers' such as typedef names). That's "OK" — you're using an incomplete type. So the code compiles. But it's not OK because you can't access the members of an incomplete type.
Presumably, what you had in mind was:
typedef struct
{
bool status;
temp_sens_t *temp_value[3];
temp_sens_t *sensors[3];
char sensor_name[MAX_LEN];
} tempsensors_t;
Note the absence of the struct
inside the structure definition.
With this revised definition, you should be able to do:
temp_t *tempinfo = &sensors[1]->temp_value[0]->temp;
tempinfo->sensnr = 1;
Working code:
#include <stdbool.h>
#include <stdint.h>
enum { MAX_LEN = 32 };
typedef struct
{
bool status;
uint8_t sensnr;
uint8_t set_vallue;
uint8_t actuval_value;
} temp_t;
typedef struct
{
uint8_t senspwrsource;
uint8_t sensnr;
uint8_t max_value;
} sensor_t;
typedef union {
temp_t temp;
sensor_t sensor;
} temp_sens_t;
typedef struct
{
bool status;
temp_sens_t *temp_value[3];
temp_sens_t *sensors[3];
char sensor_name[MAX_LEN];
} tempsensors_t;
tempsensors_t sensors[5];
extern void access_it(int i);
void access_it(int i)
{
temp_t *tinfo1 = &sensors[1].temp_value[0]->temp;
tinfo1->sensnr = i;
temp_sens_t *tinfo2 = sensors[1].temp_value[0];
/* Either of these works - choose the correct part of the union */
tinfo2->sensor.sensnr = i;
tinfo2->temp.sensnr = i;
}
Notice: GCC 10.2.0 was consulted about the accuracy of this code.
gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes -fno-common -c as41.c