bastwendo
bastwendo

Reputation: 67

Vectors passed to function aren't being modified

So I am making a function to take certatin elements of a vector and storing them into another vector. Whenever I run the program, it gives a segmentation fault error? Why does this happen and how can I fix things so that this doesn't happen?

#include <iostream>
#include <vector>
#include <string>

using namespace std;

void addition (vector <char> a, vector <string> b)
{
  for (int i = 0; i < a.size(); ++i)
  {
    if (a[i] == '3')
    {
      b.push_back("3");
    }
    if (a[i] == '4')
    {
      b.push_back("4");
    }
    if (a[i] == '+')
    {
      b.push_back("+");
    }
  }
}

int main()
{
  vector <char> v1 = {'3', '4', '+', '3', '4'};
  vector <string> v2;

  addition(v1, v2);
  cout << v2[0] << endl;

  return 0;
}

Upvotes: 1

Views: 957

Answers (3)

songyuanyao
songyuanyao

Reputation: 172924

The parameter b is declared as pass-by-value, so it's just a copy of the argument, and any modification on it inside addition() has nothing to do with the original argument passed-in (i.e. v2 in main()). Then cout << v2[0] << endl; will lead to undefined behavior (means anything is possible), because v2 is still empty.

You should change it to pass-by-reference, e.g.

void addition (vector <char> a, vector <string>& b)
//                                             ~

BTW: a should be declared as pass-by-reference too, to avoid unnecessary copy, .e.g

void addition (const vector <char>& a, vector <string>& b)

Upvotes: 5

Tanuj Yadav
Tanuj Yadav

Reputation: 1297

You have passed a new copy of the vector v2. So the changes made to v2 in the function are actually made to its copy, not v2.
As a result v2 actually remains empty, and accessing v2[0] gives segmentation fault.

Solution is to pass reference of v2 as

void addition (vector <char> a, vector <string> &b)

Upvotes: 1

Yuval Ben-Arie
Yuval Ben-Arie

Reputation: 1290

You pass a copy of the vectors and not a reference.
Change:

void addition (vector <char> a, vector <string> b)

into:

void addition (const vector <char> &a, vector <string> &b)

Note: I changed a to a reference too just to save unnecessary copies, and made it const to make sure it isn't changed.

Upvotes: 4

Related Questions