简体   繁体   English

C动态数组的空指针

[英]C Dynamic Array of void pointers

OK, so I've got the following C code: OK,所以我有以下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));
}

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? 使用realloc(myArray,newNumberOfIndices*sizeof(ElementWithBiggestSize))重新分配数组是否realloc(myArray,newNumberOfIndices*sizeof(ElementWithBiggestSize)) ,还是有一种更优雅的方法来实现这一点?

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 PS:使用具有不同结构的空指针数组进行快乐的调试

edit: renaming "b_instance to b_pointer", just trying to make it less confusing 编辑:重命名“ b_instance到b_pointer”,只是试图使它少混乱

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM