I'm struggling to create a generic (or untyped) array in C (I'm aware that C++ makes this easier). In a nutshell I want to allocate an array to hold an array of a specific known type (at runtime). In the real implementation it depends on user input.
I've been trying to use a enum/struct scenario following the advice found in several Google hits but I'm afraid that my inexperience with void pointers and lack of a concrete example are preventing me from getting a working piece of code. (Normally I would just buy a book but I'm in a country where I don't speak the language and English programming books are non-existent.)
The problem boils down to the following simplification: I have an image (only 1D) were the pixel values may be int, float, or double. I do have a function that will tell me the type. All I want to do is store the pixels in an array of the appropriate type. (In practice these images are very large and my motivation is to save memory and to prevent writing blocks of code for each type.)
I've been trying something like the following but maybe it's not the best anyway (code snippet for a possible data structure) :
enum type {
typeint, typefloat, typedouble
};
struct genericarray {
enum type type;
void *storage;
};
Somehow I want to store those pixels in instances of generciarray. All my attempts so far have turned into "warning: dereferencing ‘void *’ pointer" parties, which I admit I am not understanding.
I'm be eternally grateful for any help and in particular for some simplified example how to get a working generic array. The example could just use for-loops to init. I can figure out how to load my actual images.