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; }
kstatic incal. Which would work in his precise example, but can lead to no end of "surprising" behavior otherwise. Still, everytime the standard C library has to return a pointer, that's what it does.