簡體   English   中英

C動態數組的空指針

[英]C Dynamic Array of void pointers

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

但我希望能夠動態調整數組的大小。 我知道您可以動態調整僅包含如下類型的數組的大小:

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))重新分配數組是否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;

請注意,如果要分配指針,則要指向哪個結構或數組(或我不知道是什么)並不重要。

PS:使用具有不同結構的空指針數組進行快樂的調試

編輯:重命名“ b_instance到b_pointer”,只是試圖使它少混亂

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM