在执行时定义长度的整数数组

问题描述

我需要在函数内分配一个整数数组,然后返回它。问题是我不知道我需要分配多少内存:它可能是 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 返回的地址存储在作为参数给出的同一指针中?

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

解决方法

允许将 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;
    }
}