sateayam
sateayam

Reputation: 1089

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 different types mentioned above?

Upvotes: 2

Views: 1333

Answers (2)

Feanor
Feanor

Reputation: 670

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

Upvotes: 3

Ed Heal
Ed Heal

Reputation: 59997

You need to use union

i.e.

typedef struct {
        int type;
        union {

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

Upvotes: 1

Related Questions