【问题标题】:Array of integers with length defined at execution time长度在执行时定义的整数数组
【发布时间】:2020-12-24 19:08:12
【问题描述】:

我需要在一个函数中分配一个整数数组,然后返回它。问题是我不知道我需要分配多少内存:它可能是sizeof(int)*3,因为它可能比我得到的内存更多。

由于分配一大块内存可能是多余的或不够的,这不是一个好的解决方案,我将第一次使用realloc

现在我需要像这样循环使用它

for(i = 3; (res[i] = res[i-3] - res[i-2] - res[i-1]) >= 0; i++) {
    
    res = realloc( res, sizeof(long long) * (i+2) );
}

是否允许将realloc返回的地址存储在与参数相同的指针中?

这是创建在执行时定义的大小数组的好方法吗?

【问题讨论】:

  • 标题是“整数数组”,但您的代码中使用了sizeof(long long)。您真正想使用哪个?
  • 你说得对,我要把标题改成“整数”

标签: arrays c integer realloc execution-time


【解决方案1】:

允许将realloc返回的地址存储在与参数相同的指针中,但这不是一个好方法,因为它会阻止realloc失败时释放分配的内存。

最好先将结果存储到另一个指针中,然后检查指针是否不是NULL,然后将其分配给原始变量。

for(i = 3; (res[i] = res[i-3] - res[i-2] - res[i-1]) >= 0; i++) {
    
    long long* new_res = realloc( res, sizeof(long long) * (i+2) );
    if (new_res == NULL) {
        /* handle error (print error message, free res, exit program, etc.) */
    } else {
        res = new_res;
    }
}

【讨论】:

  • 我假设初始分配是3。所以,for中的条件是给res[i]赋值之前数组增加。这是UB吗?
  • 不,初始分配是sizeof(long long) * 4。抱歉,如果我没有发布足够的上下文
猜你喜欢
  • 2012-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多