本文介绍了如何从函数返回数组并循环通过它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include< iostream>
int * fib(int);
int main()
{
int count;
std :: cout<<输入要打印斐波那契数列的数字<< std :: endl;
std :: cin>> count;
int * p = new int [count];
p = fib(count);
int i;
for(i std :: coutreturn 0;
}
int * fib(int d)
{
int * ar = new int [d]
int p = -1,q = 1,r;
int j;
for(j = 0; j {
r = p + q;
ar [j] = r;
p = q;
q = r;
}
return ar;
delete ar;
}
为什么我无法以这种方式打印整个Fibonacci数组
解决方案
您的代码有几个问题
code> for(i
for(i = 0; i
和
; j ++)
必须读
for(j = 0; j< d; j ++)
删除该行
delete ar;
因为它在返回后没有任何效果语句。此外,你可以摆脱实例化
int * p = new int [count] $ c $ b在 fib 函数中。因为它是,你泄漏你刚刚分配的记忆。
#include <iostream> int* fib(int); int main() { int count; std::cout<<"enter number up to which fibonacci series is to be printed"<<std::endl; std::cin>>count; int *p=new int[count]; p=fib(count); int i; for(i<0;i<=count;i++) std::cout<<p[i]<<std::endl; return 0; } int* fib(int d) { int *ar=new int[d]; int p=-1,q=1,r; int j; for(j=0;j<=d;j++) { r=p+q; ar[j]=r; p=q; q=r; } return ar; delete ar; }Why am I not able to print the whole array of Fibonacci series in this way?
解决方案Several issues with your code
for(i<0;i<=count;i++)should actually be
for(i=0;i<count;i++)and
for(j=0;j<=d;j++)must read
for(j=0;j<d;j++)And remove the line
delete ar;since it does not have any effect after the return statement. Additionally you can get rid of the instantiation
int *p=new int[count];in main() since this is done in your fib function also. As it stands, you leak the memory you just allocated.
这篇关于如何从函数返回数组并循环通过它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!