C/arrays of different sized elements
Expert: Kedar Desai - 11/9/2011
QuestionHi,
I'd want to know if there is any way in C to do the following/
-create an array with different sized elements; e.g sizeof(arr[0]) could be 4 bits, and that of the other elements 6 bits, 10 bits or a byte.
Thanks in advance!!!
AnswerNo, in C each element of an array have to be of the same type (and thus the same size as well).
I searched a lot on this topic and i found the following answer :
You might need to add another layer of abstraction, in this case you need to annotate the elements with the type it has e.g. you could make an array of struct that look like:
enum ElemType {
TypeNull,
TypeFoo,
TypeBar
};
struct Elem {
enum ElemType type;
void *realElem;
};
You'd have to update the 'type' with the actual type you insert, and make decisions on that when you read the array, and you store a pointer to the actual element in the 'realElem' member.
struct Elem arr[42];
...
switch(arr[k].type) {
case TypeFoo:
handleFoo(arr[k].realElem);
break;
...
}