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.

Community
  • 1
  • 1
Gautam Kumar
  • 1,162
  • 3
  • 14
  • 29
  • 3
    You might want to wait for an answer to [another of your questions](http://stackoverflow.com/questions/5927023/how-to-return-an-array-to-a-function) and not ask two very similar ones right after each other. – Bart May 08 '11 at 11:07
  • 1
    The easiest way is to use a std::vector instead of an array. :-) – Bo Persson May 08 '11 at 11:12

1 Answers1

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);
aroth
  • 54,026
  • 20
  • 135
  • 176
  • 1
    If you replace `int*` with `shared_array`, then replace the `malloc` with `new[]`, and remove the `free`, then yes. – Collin Dauphinee May 08 '11 at 11:20
  • 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 []? – Martin York May 08 '11 at 11:25
  • 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. – Martin York May 08 '11 at 11:29