I want to store mixed data types in an array. How could one do that?
ベストアンサー1
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];
メンバーは、各配列要素にtype
のどのメンバーを使用するかの選択を保持するために使用されますunion
。したがって、最初の要素に を格納する場合はint
、次のようにします。
my_array[0].type = is_int;
my_array[0].val.ival = 3;
配列の要素にアクセスする場合は、まず型を確認し、次に共用体の対応するメンバーを使用する必要があります。ステートメントswitch
が便利です。
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
}
type
メンバーが常に に格納されている最後の値に対応するようにするのはプログラマの責任ですunion
。