【问题标题】:realloc an array with c用 c 重新分配一个数组
【发布时间】:2020-05-13 11:37:38
【问题描述】:

我试图找到与我类似的标题问题,但没有找到我想要的。所以这是我的问题。 如果我 malloc 一个大小为 10 的数组,它是否能够重新分配大小并使其变为 9?还有8等?如果可以的话,如果我有这个数组: [1,2,3,4,5,6,7,8,9,10] 我怎么知道哪个单元格会被删除?每次都可以选择删除哪一个吗?

【问题讨论】:

  • 说明书上不是很清楚吗? realloc()函数尝试将ptr指向的分配大小改变为size,并返回ptr。
  • 为什么不能呢? realloc 的重点是改变大小。请在您的问题中添加详细信息。
  • Is it able to choose which one to delete every time ? - 不,您只能从末尾删除或添加到末尾。
  • 不,你不能选择。如果大小减小,则数组的末尾会丢失。还涵盖在realloc man pageThe contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes
  • 谢谢@500-InternalServerError 。但是如果我把 2 换成 10,把 2 删掉,然后再把 10 放在最后呢?你认为这会奏效吗?

标签: c malloc realloc


【解决方案1】:

当您realloc 具有较小的大小时,许多实现什么都不做:您有一个可以容纳至少 10 个元素的块,它可以容纳至少 8 个元素。简单地说,您将不再使用超过声明大小的元素。没有什么能阻止你这样做,但它只是调用未定义的行为。

对于初学者来说可能会感到惊讶:

int *arr = malloc(10 * sizeof(int));   // allocate an array of 10 int
for (int i=0; i<10; i++) {             // initialize it with 0-9
    arr[i] = i;
}
arr = realloc(arr, 8*sizeof(int));     // realloc the array to 8 elements
for (int i=0, i<8; i++) {
    printf(" %d", i);
}
printf("\n");                          // should have correctly printed 0 1 ... 7
// the interesting part
for (int i=8; i<10; i++) {
    printf(" %d", i);                  // Oops, UB!
}
printf("\n");                          // but what is to be expected is just 8 9...

现在它可以工作,但是是 UB。换一种说法永远不要假装我说它是正确的代码。但大多数实现都会接受它并给出预期的结果(UB 允许...)而没有任何其他副作用。

【讨论】:

    【解决方案2】:

    realloc() 和 reallocarray() 函数用于此目的。 方法头其实是:

    void *realloc(void *ptr, size_t size);
    void *reallocarray(void *ptr, size_t nmemb, size_t size);
    

    其中 *ptr 是指向要重新分配的内存的指针。

    但是,您无法选择。如果增加大小,旧元素将保持原样,最后会有一些未定义的元素(null)。如果你减少它,内存空间将被“削减”,这意味着,如果你有 10 个元素的空间,而你重新分配 6 个元素,最后 4 个元素将无法访问。

    如果您想实现该行为,请在重新分配之前安排您的数组

    可以在手册页 (enter link description here) 和多个网站中找到更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-23
      • 2014-07-14
      • 2016-07-31
      • 1970-01-01
      • 2012-06-17
      • 2011-10-28
      • 1970-01-01
      • 2011-03-12
      相关资源
      最近更新 更多