开发者

Create an array with elements of different types

I need to declare an array that consists of different variable types, mainly:

char *A; uint32_t B; int C;

As I understood in the tutorials, in the array you declare the type and the number of element. So to say something like:

int a[3];

where in this case, the type of the three elements are all integers. So how do I want to declare an array that consists of the three di开发者_如何学Pythonfferent types mentioned above?


The definition of an array in C is a collection of elements of the SAME type. What you are looking for is probably a 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;
}

Or, as mentioned in a comment below, you could use a union instead. But then you can't use A, B, and C at the same time like I have in the example above - only one of them will be stored - in my example it would be C.

You can make an array of structures if you need to.

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


You need to use union

i.e.

typedef struct {
        int type;
        union {

        char *A;
        uint32_t B;
        int C; 
        }} item;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜