我只是在玩 C 语言,我想要一个函数来生成斐波那契数列直到可变的最大项,并作为指向数组的指针返回。下面的代码工作得很好。
但我的问题实际上是它是否可以优化?我正在生成相同的斐波那契数列两次;首先找到有多少 fibterms 直到 maxterm 并分配足够的内存来容纳所有的术语,然后第二次用我的术语填充那个内存现在发现了两次。
我是不是忽略了 malloc() 的一些更关键的东西,或者有没有办法将这两个循环结合起来?我可以不断地调用 malloc 并将旧的 fib 复制到新的吗?反复调用新内存有那么糟糕吗?
int* genFib(int maxterm)
{
// generate a way for x to be the fibonacci term
// with y being the previous term
int x = 1, y = 1;
// fibterms is a global variable that counts the
// number of terms, to create the right size array.
// it needed to be global to find the size elsewhere
do
{
int temp = x;
x += y;
y = temp;
fibterms++;
}
while (x < maxterm);
// the array has enough space allocated now, but
// is empty for the moment.
int* fib = malloc(sizeof(int) * fibterms);
// i need to now redo my previous loop just to
// fill the array with the correct terms, so all
// counters and terms are reset.
x = 1, y = 1;
fibterms = 0;
// same loop as above, but
// filling the array this time
do
{
fib[fibterms] = x;
int temp = x;
x += y;
y = temp;
fibterms++;
}
while (x < maxterm);
return fib;
}
最佳答案
int* fib = malloc(sizeof(int));
x = 1, y = 1;
fibterms = 0;
// same loop as above, but
// filling the array this time
do
{
fib[fibterms] = x;
int temp = x;
x += y;
y = temp;
fibterms++;
fib = (int *)realloc(fib , sizeof(int)*(fibterms+1));//fibterms is a int from 0
}
关于c - 如何优化 malloc() 或动态填充未知大小的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20989662/