0

Possible Duplicate:
howto return a array in a c++ method?

How an array can be returned from a function in c++?please accomplish your answer with a simple example too if possible.thankx in advance.

2
  • 3
    You might want to wait for an answer to another of your questions and not ask two very similar ones right after each other. Commented May 8, 2011 at 11:07
  • 1
    The easiest way is to use a std::vector instead of an array. :-) Commented May 8, 2011 at 11:12

1 Answer 1

2

Return a pointer to the start of the array, like:

int* getArray(int numElements) {
   int* theArray = malloc(sizeof(int) * numElements);
   return theArray;
}

...you can use it like:

int* myArray = getArray(3);
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;

//do this when you are done with it
free(myArray);
Sign up to request clarification or add additional context in comments.

3 Comments

If you replace int* with shared_array, then replace the malloc with new[], and remove the free, then yes.
A perfect example of why not to use pointers. The is no indication that the function is returning ownership of a dynamically allocated block. Thus how does the caller know the returned pointer should be de-allocated. If by some magic you know it needs to be de-allocated then how does the caller know how to perform that task free(), delete, delete []?
In C++ code you should rarely pass around RAW pointers. Internally to a component there is some leeway but it should never pass through an external interface to code that belongs to another developer. This is because there is no concept of ownership. Without knowing who owns a pointer there is no understanding of who should release the pointer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.