I want to store mixed data types in an array. How could one do that?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- How to get the maximum of more than 2 numbers in V
- Faster loop: foreach vs some (performance of jsper
- Convert Array to custom object list c#
Array elements need to have the same size, that is why it's not possible. You could work around it by creating a variant type:
The size of the element of the union is the size of the largest element, 4.
You can make the array elements a discriminated union, aka tagged union.
The
type
member is used to hold the choice of which member of theunion
is should be used for each array element. So if you want to store anint
in the first element, you would do: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:It's left up to the programmer to ensure that the
type
member always corresponds to the last value stored in theunion
.You can do a
void *
array, with a separated array ofsize_t.
But you lose the information type.If you need to keep information type in some way keep a third array of int (where the int is an enumerated value) Then code the function that casts depending on the
enum
value.Use a union:
You will have to keep track of the type of each element, though.
Union is the standard way to go. But you have other solutions as well. One of those is tagged pointer, which involves storing more information in the "free" bits of a pointer.
Depending on architectures you can use the low or high bits, but the safest and most portable way is using the unused low bits by taking the advantage of aligned memory. For example in 32-bit and 64-bit systems, pointers to
int
must be multiples of 4 (assumingint
is a 32-bit type) and the 2 least significant bits must be 0, hence you can use them to store the type of your values. Of course you need to clear the tag bits before dereferencing the pointer. For example if your data type is limited to 4 different types then you can use it like belowIf you can make sure that the data is 8-byte aligned (like for pointers in 64-bit systems, or
long long
anduint64_t
...), you'll have one more bit for the tag.This has one disadvantage that you'll need more memory if the data have not been stored in a variable elsewhere. Therefore in case the type and range of your data is limited, you can store the values directly in the pointer. This technique has been used in the 32-bit version of Chrome's V8 engine, where it checks the least significant bit of the address to see if that's a pointer to another object (like double, big integers, string or some object) or a 31-bit signed value (called
smi
- small integer). If it's anint
, Chrome simply does an arithmetic right shift 1 bit to get the value, otherwise the pointer is dereferenced.On most current 64-bit systems the virtual address space is still much narrower than 64 bits, hence the high most significant bits can also be used as tags. Depending on the architecture you have different ways to use those as tags. ARM, 68k and many others can be configured to ignore the top bits, allowing you to use them freely without worrying about segfault or anything. From the linked Wikipedia article above:
On x86_64 you can still use the high bits as tags with care. Of course you don't need to use all those 16 bits and can leave out some bits for future proof
In prior versions of Mozilla Firefox they also use small integer optimizations like V8, with the 3 low bits used to store the type (int, string, object... etc.). But since JägerMonkey they took another path (Mozilla’s New JavaScript Value Representation, backup link). The value is now always stored in a 64-bit double precision variable. When the
double
is a normalized one, it can be used directly in calculations. However if the high 16 bits of it are all 1s, which denote an NaN, the low 32-bits will store the address (in a 32-bit computer) to the value or the value directly, the remaining 16-bits will be used to store the type. This technique is called NaN-boxing or nun-boxing. It's also used in 64-bit WebKit's JavaScriptCore and Mozilla's SpiderMonkey with the pointer being stored in the low 48 bits. If your main data type is floating-point, this is the best solution and delivers very good performance.Read more about the above techniques: https://wingolog.org/archives/2011/05/18/value-representation-in-javascript-implementations
There's a different style of defining the tag-union (by whatever name) that IMO make it much nicer to use, by removing the internal union. This is the style used in the X Window System for things like Events.
The example in Barmar's answer gives the name
val
to the internal union. The example in Sp.'s answer uses an anonymous union to avoid having to specify the.val.
every time you access the variant record. Unfortunately "anonymous" internal structs and unions is not available in C89 or C99. It's a compiler extension, and therefore inherently non-portable.A better way IMO is to invert the whole definition. Make each data type its own struct, and put the tag (type specifier) into each struct.
Then you wrap these in a top-level union.
Now it may appear that we're repeating ourselves, and we are. But consider that this definition is likely to be isolated to a single file. But we've eliminated the noise of specifiying the intermediate
.val.
before you get to the data.Instead, it goes at the end, where it's less obnoxious. :D
Another thing this allows is a form of inheritance. Edit: this part is not standard C, but uses a GNU extension.
Up-casting and down-casting.
Edit: One gotcha to be aware of is if you're constructing one of these with C99 designated initializers. All member initializers should be through the same union member.
The
.tag
initializer can be ignored by an optimizing compiler, because the.int_
initializer that follows aliases the same data area. Even though we know the layout (!), and it should be ok. No, it ain't. Use the "internal" tag instead (it overlays the outer tag, just like we want, but doesn't confuse the compiler).