codeflow
codeflow

Reputation: 13

How can I return a pointer to an array in C++?

Here is my simple code arrayfunc() should store some numbers in an array, and return the pointer of this array to main function where the content of the array would be printed What is the problem with my code? It only returns the pointer to the first element of the array Any help will be appreciated. Thanks in advance.


   #include <iostream>

   using namespace std;

   //The definition of the function should remain the same
   int* arrayfunc()
   {
    int *array[10];
    array[0] =new int;
    array[1] =new int;
    array[2] =new int;
    array[3] =new int;

    *array[0]=10;
    *array[1]=11;
    *array[2]=12;
    *array[3]=13;

    return  *array;

   }

   int main()
   {


    for(int i=0;i<4;i++)
    cout<<*(arrayfunc()+i)<<endl; 

     return 0;
   }

Upvotes: 0

Views: 9427

Answers (5)

Vlad
Vlad

Reputation: 35594

Your array is allocated on stack, so as soon as the function returns, it's freed. So you want to return a pointer to a dead memory.

But you are not doing that, you are just returning the valid (copy of) value of the 0th array item.

So, what you have to do:

  1. The best idea would be to switch to stl containers. You should be using std::vector or something like that.
  2. If you stick to the idea of manual memory management, you have to allocate the array on heap, return it from the function, and perhaps deallocate it in the caller.

Edit:
basically you want the following:

using namespace std;

vector<int> arrayfunc()
{
    vector<int> v;
    v.push_back(10);
    ...
    return v;
}

...

vector<int> result = arrayfunc();
cout << result[0] << ...

This would be the right C++ way.

(Nitpicking:) You don't need to care about copying the vector, because of the RVO used by all modern C++ compilers.


Allocating an array on heap should be simple, too:

int* array = new int[4];
array[0] = 10;
...
return array;

...
int* array = arrayfunc();
...
delete[] array;

But I would strongly advise to take the former approach (with vector).

Upvotes: 1

amit
amit

Reputation: 178451

(1) You should allocate your array with new if you want to return it: int* array = new int[10]; [assuming here you want array of ints and not array of int*'s]
(2) to return the pointer to the first element in the array, use return array and not return *array
(3) your array is array of pointers, and not array of ints.

Upvotes: 3

Abed Hawa
Abed Hawa

Reputation: 1362

Just try return array; instead of return *array;

Upvotes: 0

talkol
talkol

Reputation: 12887

This codes seems wrong to me in several levels.

  1. Never return an internal variable of a function. The variable array is only defined in the function, so it should never be returned outside.

  2. Why do you allocate each int by itself with new? I would allocate the entire array at once. If you know the array length and it's constant, consider having it defined statically.

Upvotes: 1

Related Questions