【问题标题】:Create an array with elements of different types创建一个包含不同类型元素的数组
【发布时间】:2011-11-30 13:42:03
【问题描述】:

我需要声明一个由不同变量类型组成的数组,主要是:

char *A; uint32_t B; int C;

正如我在教程中所理解的,在数组中声明元素的类型和数量。可以这么说:

int a[3];

在这种情况下,三个元素的类型都是整数。 那么如何声明一个包含上述三种不同类型的数组呢?

【问题讨论】:

    标签: c


    【解决方案1】:

    C 中数组的定义是 SAME 类型的元素的集合。您正在寻找的可能是struct。

    struct s
    {
        char* A;
        uint32_t B;
        int C;
    };
    
    int main(void)
    {
        struct s test;
        test.A = "Hello";
        test.B = 12345;
        test.C = -2;
    
        // Do stuff with 'test'
        return 0;
    }
    

    或者,正如下面评论中提到的,您可以改用union。但是你不能像我在上面的例子中那样同时使用 A、B 和 C - 只有其中一个会被存储 - 在我的例子中它将是 C。

    如果需要,您可以创建一个结构数组。

    struct s test[5];  // Array of structures
    

    【讨论】:

    • 问题是:我需要将我的结构成员放在一个数组中,并对这个数组变量做一些事情。所以这是不可能的?
    • 请注意,您可以有一个structs 数组,即在struct whatever array[100] 中,array 有100 个元素,所有类型均为struct whatever。
    【解决方案2】:

    你需要使用union

    即

    typedef struct {
            int type;
            union {
    
            char *A;
            uint32_t B;
            int C; 
            }} item;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-14
      • 2021-07-02
      • 1970-01-01
      • 2021-11-04
      • 2014-05-02
      • 2014-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多