First of all int x = {1,2,3}
is syntax error. It should be int x[] = {1,2,3};
This is undefined behaviour. Because the automatic array has a lifetime inside its block where it is defined, that is inside the foo()
function. So whenever you return from foo()
the storage for x
is no more guaranteed to be reserved for you. Therefore if you access that location through pointers then the behaviour is undefined.
To achieve the same result dynamically allocate memory.
int *foo(void){
int x[] = {1,2,3}, *x_to_return;
x_to_return = new int [sizeof (x)/sizeof(x[0])];
memcpy (x_to_return, x, sizeof (x));
return x_to_return;
}
Basically, what you need to do is to dynamically allocate the storage using new
, copy your data to the block of memory (base of which is) allocated by new
and return that memory address to the caller.
Don't forget to free the allocate the memory once you have finished using it, else your code would have memory leakage.
Also a point to be noted, if you have a declaration like static int x[] = {1,2,3};
then you can return the address of x
, because in this case the lifetime of x
is the entire program runtime.
As your question is tagged c++ you should use vector
, check moooeeeep's answer.