0

I have to return vector from a function. I tried by returning the value and also passing it as reference. but i get junk values. The below program gives the following output.

 **This is the print inside the function**
 1 7 8  
 1 2 3 
 4 5 6 

 **This is the print using the return value /  referenced value outside the function**. 
 1 7 8 
 46980021526656 46980019425190 0 
 1 46980021526656 6

#include <iostream>
#include<vector>
using namespace std;

void process(vector<unsigned long long int*> &vec)
{
    //vector<unsigned long long int*> vec;
    unsigned long long int a[] ={1,2,3};
    unsigned long long int b[] = {4,5,6};
    vec.push_back(a);
    vec.push_back(b);

    for (int i = 0;i < vec.size();i++)
    {
        for (int j = 0;j < 3;j++)
        {
            cout << vec[i][j] << " ";
        }
        cout << "\n";
        }
    cout << "\n";

//return vec;
}

int main() {
// your code goes here
vector<unsigned long long int*> vec;
unsigned long long int c[] ={1,7,8};
vec.push_back(c);
process(vec);
for (int i = 0;i < vec.size();i++)
{
    for (int j = 0;j < 3;j++)
    {
        cout << vec[i][j] << " ";
    }
    cout << "\n";
}
cout << "\n";
return 0;
}

I dont know what went wrong. I referred many stack overflow posts . But i couldnt find the solution

Please do point out what i am doing wrong. Thanks in advance

sesh
  • 23
  • 4

2 Answers2

6

Please do point out what i am doing wrong

your code is :

void process(vector<unsigned long long int*> &vec)
{
    //vector<unsigned long long int*> vec;
    unsigned long long int a[] ={1,2,3};
    unsigned long long int b[] = {4,5,6};
    vec.push_back(a);
    vec.push_back(b);

so process memorize in vec addresses of local variables a and b, when you go back in main these local variables do not exist anymore, the content they have is undefined/broken so in main you write undefined values

vec.push_back(a); does not copy a, that just pushes the address of a

bruno
  • 32,421
  • 7
  • 25
  • 37
2

Try with Standard Library arrays:

#include <iostream>
#include <vector>
#include <array>
using namespace std;

void process(vector<array<int, 3>> &vec)
{
    //vector<unsigned long long int*> vec;
    array<int, 3> a{1, 2, 3};
    array<int, 3> b{4, 5, 6};
    vec.push_back(a);
    vec.push_back(b);

    for (int i = 0; i < vec.size(); i++)
    {
        for (int j = 0; j < 3; j++)
        {
            cout << vec[i][j] << " ";
        }
        cout << "\n";
    }
    cout << "\n";

    //return vec;
}
int main()
{
    // your code goes here
    vector<array<int, 3>> vec;
    array<int, 3> c{1, 7, 8};
    vec.push_back(c);
    process(vec);
    for (int i = 0; i < vec.size(); i++)
    {
        for (int j = 0; j < 3; j++)
        {
            cout << vec[i][j] << " ";
        }
        cout << "\n";
    }
    cout << "\n";
    return 0;
}
Souyama
  • 116
  • 2
  • 10