You are here:

C/arrays of different sized elements

Advertisement


Question
Hi,
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!!!

Answer
No, 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;
 ...
}

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Kedar Desai

Expertise

You can ask me any questions about C and c++

Experience

I don't have practical experience. But i have knowledge about C as I belong to IT field since last 5 years.

Education/Credentials
I an studying in MCA from Maharashtra (Mumbai University)

©2012 About.com, a part of The New York Times Company. All rights reserved.