I don't like the idea of returning a pointer andjust saying "Yeah, it's an array with two elements".
How are you supposed to know how many elements it has? Yes, in this case, you know it has two, but I don't think you should do it like that. It looks like a recipe for segmentation faults to me.
I would do it with a vector: std::vector <int> foo(int x);
or, you could "return" the value in an argument and return the number of elements as a return value, e.g.
1 2 3 4 5
int foo(int buffer[], int x)
{
/* [...] */
return number_of_elements;
}
I agree with chrisname. There are a number of solutions. I'm sure the OP is a simplification of the problem but sometimes I wonder why such a function would ever be needed in the first place. Constructing a std::vector in place is very simple so unless there is some complex algorithm for building the array and filling it I see no reason to have an additional function call.
1 2 3 4 5 6 7 8
// create a dynamic array in place. Then there is no reason to worry about the issues
// with returning an array from a function.
int x = 5;
std::vector<int> buffer(x);
// Even if you want a c-array it is fairly simple to do it in place. Why bother calling a function
// just to create it and return a pointer?
int* buffer = newint[x];
This probably contains more info then you really need but it could give you examples on how to do things like this with template programming instead of c-arrays. Ultimately you can create arrays in place and then pass the array to a function so that it is filled. I just don't see the need for a function whose sole purpose is to create an empty array and return a pointer.