【问题标题】:How can I create an array with struct elements in C?如何在 C 中创建带有结构元素的数组?
【发布时间】:2021-01-08 18:50:54
【问题描述】:

我想创建一个包含结构元素的数组,该结构的每个元素都是一个布尔值,并且在访问每个数组元素时我想修改结构的值。结构体是全局变量,修改数组元素时,我想也修改全局结构体。

typedef struct
{
    bool bool1;
    bool bool2;
    bool bool2;
} struct_bool;

struct_bool my_struct;

bool array_dummy[3] = {my_struct.bool1, my_struct.bool2, my_struct.bool3};

array_dummy[0] = true;
array_dummy[1] = true;
array_dummy[2] = false;

【问题讨论】:

    标签: arrays c struct


    【解决方案1】:

    使用指针:

    bool *array_dummy[3] = { &my_struct.bool1, &my_struct.bool2, &my_struct.bool3 };
    
    *array_dummy[0] = true;
    *array_dummy[1] = true;
    *array_dummy[2] = false;
    

    【讨论】:

      【解决方案2】:

      我推荐的方法是使用匿名结构和联合:

      typedef struct {
          union {
              struct {
                  bool bool1;
                  bool bool2;
                  bool bool3;
              };
              bool booleans[3];
          };
      } struct_bool;
      
      struct_bool my_struct;
      

      这样您就可以将元素作为结构和数组来寻址。

      my_struct.bool1 = true;
      
      my_struct.booleans[1] = true;
      my_struct.booleans[2] = false;
      

      这要归功于联合元素共享它们的内存位置。匿名结构和布尔数组都位于同一地址,因此修改一个并读取另一个将读取该修改。

      【讨论】:

      • 问题是不能保证 bool1 和 bool2 在内存中是连续的。所以 booleans[0] 是 bool1 , boolean[1] 可能是 bool2,也可能不是。
      猜你喜欢
      • 1970-01-01
      • 2016-08-13
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-09
      相关资源
      最近更新 更多