I'm very amateur when it comes to pointers. What I'm trying to do is I want to create a function which takes parameter as an array or vector and modifies their actual reference values. But I don't want to directly pass a vector as the parameter. I want to pass some variables clustered together as a vector:
void myFunction (vector <int> &a)
{
for (int i = 0; i < a.size(); i++)
a[i] = i;
}
int main()
{
int a = 5, b = 6, c = 8;
myFunction ({&a, &b, &c}); // This line shows the error. Help me to repair it.
cout << a << " " << b << " " << c << endl;
}
I tried googling and mixing &
, *
and const
in my code but nothing helped.
Edit: All I had to do was add a *
in <int>
and a const
afterwards:
void myFunction (vector <int *> const &a)
{
for (int i = 0; i < a.size(); i++)
a[i] = i;
}
int main()
{
int a = 5, b = 6, c = 8;
myFunction ({&a, &b, &c}); // This fixed the error which was showing here.
cout << a << " " << b << " " << c << endl;
}
Thanks to the person in comments who asked me to put the *
after int
. I'm very beginner so I absolutely needed help with that. Unfortunately, this community looks pretty harsh to beginners.