How do I store various types in the C array?

Asked 2 years ago, Updated 2 years ago, 46 views

In Python,

mylist = ["hello", 3, {3:5, 2:4}]
print(mylist)

I was able to put various types in one list like this way Is there a way to use it like this in C?

c array

2022-09-22 14:34

1 Answers

It's possible to make each element of the array into a union.

struct {
    enum { is_int, is_float, is_char } type;
    union {
        int ival;
        float fval;
        char cval;
    } } val;
} } my_array[10];

enum type uses the role of flagging what type you used union val is written for storing values.

For example,

to store elements
my_array[0].type = is_int; //0th element int
Save my_array[0].val.ival = 3; //int

When writing the value stored in the array, you need to check the type with the switch statement first before writing it.

switch (my_array[n].type) {
case is_int:
    // // my_array[n].ival
    break;
case is_float:
    // // my_array[n].fval
    break;
case is_char:
    // // my_array[n].cvar
    break;
default:
    // Error handling!
}


2022-09-22 14:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.