从结构指针数组访问值

时间:2021-07-01 13:25:46

标签: arrays c pointers structure

我正在尝试从结构指针数组中访问指针索引值:

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

我可以分配所有值,但无法从结构指针“temp_value[3]”中读取值。

到目前为止,我已经尝试过这样的:

temp_t *tempinfo;
tempinfo = &sensors[1]->temp_value[0];

//trying to access values like this but not working.
teminfo.sensnr ;

如何访问索引为 [0 到 2] 的结构指针数组中的值?

2 个答案:

答案 0 :(得分:0)

你(部分):

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;

不过,这并不意味着您认为它意味着什么。您定义的结构或联合都没有标签(如 struct tag { … })。您定义了一个名为 temp_sens_t 的类型,但您确实没有定义了一个类型 struct temp_sens_t(即使您定义了,它也与称为 {{1} } — 结构标记与“普通标识符”(例如 typedef 名称)位于不同的命名空间中)。那是“OK”——您使用的是不完整的类型。这样代码就编译好了。但是不行,因为不能访问不完整类型的成员。

想必,你的想法是:

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;

有了这个修改后的定义,你应该能够做到:

struct

工作代码:

temp_t *tempinfo = &sensors[1]->temp_value[0]->temp;

tempinfo->sensnr = 1;

注意:此代码的准确性已咨询 GCC 10.2.0。

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

答案 1 :(得分:-1)

就像在普通数组中一样

temp_t * tempinfo = sensors[1].temp_value[0];

因为您不是在存储指向结构的指针,而是在存储结构本身

在结构体中,你正在存储指针,正如 Andrew Henle 指出的那样。

为了获得它们的价值,你可以做

tempinfo->sensor;

点用于访问结构的成员,而箭头用于访问指向结构的指针的成员。你好像把它们换了。

相关问题