Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can mixed data types (int, float, char, etc) be stored in an array?

I want to store mixed data types in an array. How could one do that?

like image 821
chanzerre Avatar asked Oct 06 '22 16:10

chanzerre


People also ask

Can data types be mixed in an array?

We can do that but , ArrayList is the correct way to do that. Yes, We can use mixed datatypes in a single array. struct {enum { is_int, is_float, is_char } type;union {int ival;float fval;char cval;} val; } my_array[10];

How do you store multiple data types in an array?

The most simplistic way of storing objects of different data types is just by declaring the type of your Array(or Collection) as an "Object". Object[] arr = new Object[10];

Can multiple types of data be stored in a single array?

No, we cannot store multiple datatype in an Array, we can store similar datatype only in an Array.

Can an array store both integer and float variables?

Now my answer was: yes, since you can declare an array of objects and store integers and floats in it.


1 Answers

You can make the array elements a discriminated union, aka tagged union.

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

The type member is used to hold the choice of which member of the union is should be used for each array element. So if you want to store an int in the first element, you would do:

my_array[0].type = is_int;
my_array[0].val.ival = 3;

When you want to access an element of the array, you must first check the type, then use the corresponding member of the union. A switch statement is useful:

switch (my_array[n].type) {
case is_int:
    // Do stuff for integer, using my_array[n].ival
    break;
case is_float:
    // Do stuff for float, using my_array[n].fval
    break;
case is_char:
    // Do stuff for char, using my_array[n].cvar
    break;
default:
    // Report an error, this shouldn't happen
}

It's left up to the programmer to ensure that the type member always corresponds to the last value stored in the union.

like image 251
Barmar Avatar answered Oct 08 '22 05:10

Barmar