2

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?

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

the problem is : I need to put my struct members inside one array, and do something with this array variable. so it is not possible per definition?
And notice you can have an array of structs, ie in struct whatever array[100], the array has 100 elements, all of type struct whatever.
1

You need to use union

i.e.

typedef struct {
        int type;
        union {

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.