【问题标题】:Expand an Array of structs to a larger size dynamically将结构数组动态扩展为更大的大小
【发布时间】:2013-06-14 03:38:49
【问题描述】:

我有一个两难境地,我有一个包含结构数组的结构......

typedef struct Container{
    struct Inner *F;
    int length;
} Memo;

typedef struct Inner{
    int *digits;
    int length;
} Inner;

我称这个函数为:

int expandContainer(Container *container, int n)

所以基本上当我将这个“容器”传递给“expandContainer”时,我初始化了一个新的一定大小的内部数组,然后对其进行 malloc,我想让通过容器通过函数传入的内部被“扩展”并更新并在退出函数时释放临时 Inner 数组。

需要明确的是,传递给函数的 Inner 无论如何都不会被破坏,因为它将在其他地方使用它只需要字面上“扩展”以容纳比最初能力更多的数据。这是我所拥有的......

int arrayLength, i;

//Get new array length
if(((memo->length * 2) + 1) > (n * 2 + 1))
    arrayLength = ((memo->length * 2) + 1);
else
    arrayLength = (n * 2 + 1);

//Create new Array
Inner *biggerArray;

//Malloc new array of Inner Structs
biggerArray = malloc(sizeof(Inner) * arrayLength);

    //Check for errors
    if(biggerArray == NULL)
        panic("ERROR: out of memory in expandContainer()\n");

//Copy data from container->F into biggerArray
for(i=0; i<container->length; i++)
    biggerArray[i] = container->F[i];

//Initialize remaining data in biggerArray
for(i=container->length; i<arrayLength; i++)
    {
        biggerArray[i].digits = NULL;
        biggerArray[i].length = 0;
    }

//Free the old array
for(i=0; i<arrayLength; i++)
    //!!!!THIS DOESN'T WORK!!!!!
    &(memo->F[i]) = &biggerArray[i];

//free the biggerArray created in the function
free(biggerArray);

//update the length of memo
memo->length = arrayLength;

printf("-> Expanded Container capacity to %d.\n", arrayLength);

return arrayLength;

不确定我是否正确实施。

【问题讨论】:

    标签: c arrays pointers struct int


    【解决方案1】:

    对于扩展本身,您可以使用realloc。它完全符合您的需要。分配一个新的(更大的)区域,复制数据并释放旧的。

    如果你想用像 expandContainer() 这样的函数来包装它。它必须通过引用获取指针:

    int expandContainer(Container **container, int n)
    

    【讨论】:

      【解决方案2】:

      尝试使用 realloc 而不是 malloc,将新分配的指针和变量初始化为 NULL(或 0)总是一个好主意 您可以使用 memcpy 将旧数组复制到新数组(以防您想坚持使用 malloc 或更好的 calloc)

      【讨论】:

        【解决方案3】:

        这有用吗?

        //Free the old array
        free(memo->F);
        // you don't free the biggerArray, instead
        memo->F = biggerArray;
        //update the length of memo
        memo->length = arrayLength;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-11-11
          • 1970-01-01
          • 2011-08-28
          • 2010-09-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多