空指针的 C 动态数组

标签 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)) 重新分配数组是否有效,或者是否有更优雅的方法来实现这一点?

最佳答案

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/

相关文章:

c++ - 适当的散列函数来散列随机二进制字符串

C计算器代码问题

c - 如何在 C 语言中为特定的结构类型正确使用 free

java - JCheckBox数组初始化或访问问题

list - 列表与向量上的 Scala 内存问题

c++ - VirtualAlloc C++,注入(inject)的dll,asm

assembly - x86 汇编中的方括号是什么意思?

c - 在理解从 C 代码生成的基本汇编代码方面需要帮助

c++ - 如何将二进制值的字符串转换回 char

ruby - MongoDB:如何存储大数组? (ERR Document too large: This BSON documents is limited to 16777216 bytes)