Search code examples
carraysmemorydynamicrealloc

C Dynamic Array of void pointers


OK, so I've got the following C code:

//for malloc
#include <stdlib.h>

//to define the bool type
#if __STDC_VERSION__ >= 199901L
#include <stdbool.h>
#else
typedef int bool;
#endif

//define structs
typedef struct A{
   int integerValue;
    char characterValue;
} A;

typedef struct B{
    float floatValue;
    bool booleanValue;
} B;

int main(int argc, const char * argv[])
{
    //allocate a void pointer array
    void* myArray[3];

    //fill the array with values of different struct types
    myArray[0] = malloc(sizeof(A));
    myArray[1] = malloc(sizeof(B));
    myArray[2] = malloc(sizeof(A));
}

but I want to be able to dynamically resize the array. I know that you can dynamically resize an array containing just one type like this:

int* myArray;
myArray = malloc(3*sizeof(int));
myArray[0] = 3;

myArray = realloc(myArray,4*sizeof(int));
printf("%i",myArray[0]);

but how would you do this in the upper situation (it needs to be able to handle a virtually infinite number of types). Would it work to reallocate the array with realloc(myArray,newNumberOfIndices*sizeof(ElementWithBiggestSize)), or is there a more elegant way to achieve this?


Solution

  • B* b_pointer = (B*) malloc (sizeof(B*));
    void** arr = (void**) malloc (3 * sizeof(void*));
    arr[0] = b_pointer;
    
    void** new_arr = (void**) malloc (6 * sizeof(A*));
    memcpy(new_arr, arr, 3 * sizeof(A*));
    // now arr[0] == new_arr[0] == b_pointer;
    
    free(arr);
    // now new_arr[0] == b_pointer;
    

    Note that if you're allocating pointers, it doesn't really matter which struct or array (or i don't know what) you want to point to.

    PS: happy debugging using void pointer array with different structs

    edit: renaming "b_instance to b_pointer", just trying to make it less confusing