【问题标题】:Dynamically allocate memory for array in C在C中为数组动态分配内存
【发布时间】:2014-12-09 23:27:16
【问题描述】:

我为一个数组分配了内存(使用malloc),但是如果它需要更多空间怎么办,是否可以在程序中稍后扩展数组?或者也许创建一个新数组并让第一个数组中的最后一个元素指向新数组?
我知道realloc 会更容易使用,但我试图仅使用@987654323 来执行此操作@.

【问题讨论】:

  • 改变大小看 realloc
  • 我试图在不使用 realloc 的情况下仅使用 malloc
  • 查看 memcpy 的手册页,而不是在 for 循环中复制元素。但是,是的,这是正确的想法。
  • 我对 newArray=new array(array1) 这条线感到困惑,你使用的是 malloc,所以我不确定它是什么意思
  • 另外,不要强制转换从 malloc 返回的 void 指针。如果您绝对必须,请确保您#include <stdlib.h>

标签: c arrays malloc


【解决方案1】:

一般算法是

allocate array of 100
while more input
    if no-room-in-array
        allocate another array 100 bigger than the current array
        copy values from current array into newly created array
        free(current array)
        current array = newly created array (the one you copied into)
    // now there will be room, so
    put input in array

【讨论】:

  • 不要改变你的问题。如果您需要添加一些内容,请添加它。
  • 不,不是,我对当前数组 = 新创建的数组(您复制到的数组)的实现是错误的。不太清楚为什么
【解决方案2】:

是的,您可以使用realloc()。小心检查返回值之前你将它分配给原始指针。见这里:https://stackoverflow.com/a/1986572/4323

【讨论】:

  • 就像我说的我不能使用 realloc
  • @user2737810: 你在哪个平台上不能使用 realloc()?
  • 程序规范不允许重新分配
【解决方案3】:

错误的大小传递给malloc()

代码应该传递n * sizeof(int)而不是传递n字节。

// int *array1=(int *)malloc(100);
int *array1 = malloc(100 * sizeof *array1);

// int *newArray=(int *)malloc(size+100);
int *newArray =  malloc((size+100) * szeof *newArray);

其他想法包括

1) 无需投射

    int *array1 = (int *) malloc(...;
    int *array1 = malloc(...);

2) 使用memcpy() 进行简化

    // for(i=0; i<size; i++) newArray[i]=array1[i];
    memcpy(newArray, array, size * sizeof *newArray);

3) 一定要free()

4) new 是 C++ 运算符,这是 C,使用 malloc()

5) 对于size,使用size_t 而不是int

6) 呈指数增长,而不是线性增长

// int *newArray=(int *)malloc(size+100);
size_t newsize = size*3/2;
int *newArray = malloc(newsize);

7) 检查malloc() 失败

int *newArray = malloc(newsize);
if (newArray == NULL && newsize > 0) Handle_Failure();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 2021-07-17
    • 2013-05-24
    • 2015-08-09
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    相关资源
    最近更新 更多