Reputation: 1633
I came across something rather strange and I couldn't find anything reasonable. I wrote a function like this that returns an int pointer like this:
int* arr()
{
int array[3]={1,2,3};
return array;
}
now in the main, I declared an int pointer like k:
int*k=arr();
it worked perfectly OK,but here is the strange thing, I could only use one of the blocks, k[0] or k[1] or k[3] and it would print the correct corresponding number but when wanted to use it in a for like this only the first one would print correctly:
for(int i=0;i<3;i++)
{
cout<<k[i]<<endl;
}
for k[0],the printed value was correct but for the others it was something odd. I want to know if I didn't used the pointers correct why could I access each block?
Upvotes: 1
Views: 131
Reputation: 2555
You are returning a pointer to an object (here an array) that was created on a functions stack. You could use std::vector for example to pass an array from a function to the caller.
std::vector< int > arr()
{
std::vector< int > array = { 1, 2, 3 };
return array;
}
Upvotes: 5
Reputation: 64203
You didn't use it correctly. This function is returning a pointer to an array that gets destructed at the end of the function :
int* arr()
{
int array[3]={1,2,3};
return array;
}
that means, your program invokes an undefined behavior, and then anything may happen.
If you do not want to make your array global, then make it a static :
int* arr()
{
static int array[3]={1,2,3};
return array;
}
Upvotes: 3
Reputation: 71899
It's a wrong use. The array is local to the function, so the pointer you return becomes invalid the moment you're leaving the function. The memory could be reused at any moment after that.
(In particular, in this concrete instance, without implying that such behavior is in any way guaranteed, in your example loop, the functions that print the first integer overwrite the others with their local variables.)
Upvotes: 2
Reputation: 234635
int array[3]={1,2,3};
is stack-allocated. It will go out of scope at the end of the function.
You'll be accessing a dangling pointer. That's undefined behaviour. Boom!
Upvotes: 6