I am trying to return an array from a function:
#include <iostream> using namespace std; int* uni(int *a,int *b) { int c[10]; int i=0; while(a[i]!=-1) { c[i]=a[i]; i++; } for(;i<10;i++) c[i]=b[i-5]; return c; } int main() { int a[10]={1,3,3,8,4,-1,-1,-1,-1,-1}; int b[5]={1,3,4,3,0}; int *c=uni(a,b); for(int i=0;i<10;i++) cout<<c[i]<<" "; cout<<"\n"; return 0; } I pass two arrays from my main() into my uni() function. There I create a new array c[10] which I return to my main(). In my uni() function I try to merge the non-negative numbers in the two arrays a and b.
But I get something like this as my output.
1 -1078199700 134514080 -1078199656 -1216637148 134519488 134519297 134519488 8 -1078199700 Whereas when I try to print the values of c[10] in the uni() function it prints the correct values. Why does this happen?? Is this something related to the stack?? Because I have tried searching about this error of mine, and I found a few places on stackoverflow, where it says that do not allocate on stack but I couldn't understand it.
Further it would become very easy if I allocate my array globally, but if this is the case then everything shall be declared globally?? Why are we even worried about passing pointers from functions?? (I have a chapter in my book for passing pointers)
std::arrayorstd::vector. Slinging pointers to C-style arrays back and forth is extremely messy and error-prone.