C动态数组的void指针

时间:2013-11-05 17:23:07

标签: c arrays memory dynamic realloc

好的,所以我有以下C代码:

//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));
}

但我希望能够动态调整数组大小。我知道你可以动态调整一个只包含这种类型的数组:

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

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

但是如何在高级情况下执行此操作(它需要能够处理几乎无限多种类型)。是否可以使用realloc(myArray,newNumberOfIndices*sizeof(ElementWithBiggestSize))重新分配数组,还是有更优雅的方法来实现这一目标?

1 个答案:

答案 0 :(得分:1)

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;

请注意,如果您正在分配指针,那么您想要指向哪个结构或数组(或者我不知道是什么)并不重要。

PS:使用具有不同结构的void指针数组进行快乐调试

编辑:将“b_instance重命名为b_pointer”,只是试图减少混乱