[SOLVED] Return an array without getting a Dangling pointer as result in C++

Issue

I want to return an array from a function in C++. I made this simple code to try to achieve it.

#include <iostream>
#include <vector>

std::vector<int> *getx()
{
   std::vector<int> a[2];
   a[0].push_back(0);
   a[1].push_back(1);
   return a;
}

int main()
{
   std::vector<int>* b = getx();
   return 0;
}

It works but I get this Warning:

warning C4172: returning address of local variable or temporary: a

Why if i made std::vector<int> a[2] static I solve the warning?

static std::vector<int> a[2];

Is there another way to return an array from a function without having dangling pointers warnings?

Thank you.

Solution

Why if i made std::vector a[2] static I solve the warning?

static std::vector a[2];

You may not return a pointer to a local array with automatic storage duration because the array will not be alive after exiting the function and as a result the returned pointer will be invalid.

But you may return a pointer to a local array with static storage duration because it will be alive after exiting the function.

However in fact there is no need to deal exactly with an array. Either use std::vector<std::vector<int>> or std::array<std::vector<int>, 2> as the return type of the function.

For example

std::vector<std::vector<int>> getx()
{
   std::vector<std::vector<int>> a( 2 );

   a[0].push_back(0);
   a[1].push_back(1);

   return a;
}

or

std::array<std::vector<int>, 2> getx()
{
   std::array<std::vector<int>, 2> a;

   a[0].push_back(0);
   a[1].push_back(1);

   return a;
}

Answered By – Vlad from Moscow

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.