好的,所以我得到了以下 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))
重新分配数组是否有效,或者是否有更优雅的方法来实现这一点?
最佳答案
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”,只是想让它不那么困惑
关于空指针的 C 动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19794998/