I have search about auto for but still here is coming segmentation fault

Viewed 36

can anyone see my code why it is showing segmentation fault input: 3 def de fgh

#include<bits/stdc++.h>
using namespace std;


int main()
{
    vector<string> v;
    int n;
    cin >> n;
    for (int i = 0; i < n; ++i)
    {
        cin >> v[i];
    }
    for(auto x : v)
        cout << x << endl;

    return 0;
}
1 Answers

In this line,

cin >> v[i];

you request a reference to the ith element in v, but the vector is empty. You can change the part before the loop to

vector<string> v;
int n;
cin >> n;
v.resize(n); // <= this one is required.

to setup the vector such that it contains n default-constructed elements (in this case, zeros). Then it's valid to access v[i] within the correct bounds.

Related