A part of my attempts to replicate C++ style OO, I have needed to create an array of "Catalogue" Structs, which include a void pointer and a tag which tells me what type of struct the void pointer points to. This is done so that I may keep structs of different types in the same array, and then downcast them later to use their fields.
Now, the problem I have is this. After casting the newly created and initialized struct to a void pointer and assigning it to my "Catalogue" struct. Afterwards however, when I downcast the pointer to its original type, it has reset all the values the old struct contained to default values.
I have tested it out by, after inititializing the values of the intial struct and assigning it to the void pointer in the "Catalogue", immediately downcasting the pointer again and dereferencing the variables it contains and then printing them to the screen. I can see immediately as soon as I downcast it back to its original struct pointer type that the variables it used to contain have been set to NULL or 0.
The memory allocation and assignment code in generic form is listed below:
Now I honestly do not know why the variables contained within the struct pointer are reset after it has been cast to void. Does anybody have an idea of what I am doing wrong in this casting? Any help would be much appreciated :PCode:SomeStruct *structpointer = (SomeStruct*)malloc(sizeof(SomeStruct)); /*cataloguepointer is a pointer to a struct type CatalogueStruct, declared in the header*/ cataloguepointer[ cataloguecounter] = (CatalogueStruct*)malloc(sizeof(CatalogueStruct)); structpointer->var = inVar; cataloguepointer[ cataloguecounter]->voidpointer = (void*)structpointer; cataloguepointer[ cataloguecounter]->tag = "StructPointer"; /*Now trying to downcast and dereference*/ printf("Variable in Catalogue is %d\n", (((StructPointer*)(cataloguepointer[ cataloguecounter]))->var);