从C中的函数指针返回++ [英] Returning Pointer from a Function in C++
本文介绍了从C中的函数指针返回++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我从函数返回的指针,其值可单独访问。但是,当一个环被用来OUPUT该指针变量的值,错误值被示出。在那里我会犯错,不能看着办吧。
的#include<&iostream的GT;
#包括LT&;&CONIO.H GT;为int * CAL(INT *,诠释*);使用命名空间std;诠释的main()
{
诠释一个[] = {5,6,7,8,9};
INT B〔] = {0,3,5,2,1};
INT * C;
C = CAL(A,B); //此处错误outpur
/ *的for(int i = 0;我小于5;我++)
{
COUT<< *(C + I);
} * / 这里//正确的输出
COUT<< *(C + 0);
COUT&所述;&所述; *(C + 1);
COUT<< *(C + 2);
COUT<< *(C + 3);
COUT<< *(C + 4);返回0;
}为int * CAL(INT * D,INT * E)
{
INT K表[5];
为(中间体J = 0; J&小于5; J ++)
{
*(K + J)= *(D + J) - *(E + J);
}
复位K;
}
解决方案
的时int k [5]
数组在栈上创建的。因此,当它超出范围由 CAL
返回它就会被销毁。你可以使用第三个参数作为输出数组:
无效CAL(INT * D,INT * E,为int * K)
{
为(中间体J = 0; J&小于5; J ++)
{
*(K + J)= *(D + J) - *(E + J);
}
}
通话 CAL
是这样的:
int类型的[] = {5,6,7,8,9};
INT B〔] = {0,3,5,2,1};
诠释三[5];
CAL(A,B,C); //从加州回来后,C将与期望的值填充
When I return pointer from the function, its value can be accessed individually. But when a loop is used to ouput the value of that pointer variable, wrong value is shown. Where I am making mistake, can't figure it out.
#include <iostream>
#include <conio.h>
int *cal(int *, int*);
using namespace std;
int main()
{
int a[]={5,6,7,8,9};
int b[]={0,3,5,2,1};
int *c;
c=cal(a,b);
//Wrong outpur here
/*for(int i=0;i<5;i++)
{
cout<<*(c+i);
}*/
//Correct output here
cout<<*(c+0);
cout<<*(c+1);
cout<<*(c+2);
cout<<*(c+3);
cout<<*(c+4);
return 0;
}
int *cal(int *d, int *e)
{
int k[5];
for(int j=0;j<5;j++)
{
*(k+j)=*(d+j)-*(e+j);
}
return k;
}
解决方案
The int k[5]
array is created on the stack. So it gets destroyed when it goes out of scope by returning from cal
. You could use a third parameter as an output array:
void cal(int *d, int *e, int* k)
{
for(int j=0;j<5;j++)
{
*(k+j)=*(d+j)-*(e+j);
}
}
call cal
like this:
int a[]={5,6,7,8,9};
int b[]={0,3,5,2,1};
int c[5];
cal (a, b, c); // after returning from cal, c will be populated with desired values
这篇关于从C中的函数指针返回++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文