1

I'm a newbie in C++. I've just learnt about vector in STL.

However, when I tried to input an integer into my vector:

vector<int> v;
cin>>v[i]

The program returned segmentation fault. Please help me out.

Mat
  • 202,337
  • 40
  • 393
  • 406
Shrike Danny
  • 139
  • 1
  • 8
  • https://stackoverflow.com/questions/5001156/writing-integer-input-to-vector-container-in-c – Mary Apr 15 '19 at 04:58
  • Try this https://stackoverflow.com/questions/5001156/writing-integer-input-to-vector-container-in-c – Mary Apr 15 '19 at 04:59
  • We cannot compile your code without a main() function and all necessary include statements. What you have posted does not compile, so there must be more :). – Gardener Apr 15 '19 at 05:03

1 Answers1

3

Your vector doesn't have any elements in it, so the internal array is null. When you try to read something into it, you're trying to deference a null pointer (resulting in the segfault). Add elements to the vector first:

vector<int> v(100); //Create vector with 100 elements

for(int i = 0; i < 100; i++) {
    cin >> v[i]; 
}

Alternatively, you could read elements into a local variable, then add them into the vector:

vector<int> v; 
for(int i = 0; i < 100; i++) {
    int new_val;
    cin >> new_val;
    v.push_back(new_val); 
}
Alecto Irene Perez
  • 10,321
  • 23
  • 46