Passing a vector as an argument and using it, why is it crashing?

I am new to C ++, especially to STL. I am trying to pass a vector as an argument to a function, but this causes the application to crash. I am using Code :: Blocks and MingW. Here is a simple code.

#include <iostream> #include <vector> using namespace std; void foo(const vector<int> &v) { cout << v[0]; } int main(){ vector<int> v; v[0] = 25; foo(v); return 0; } 

Thanks!

+6
source share
1 answer

It crashes because you write beyond the end of the vector with v[0] - that is undefined. Its actual size is 0 if you are not doing anything. (You also read the same, but all bets come out well before that point).

You probably wanted to:

 vector<int> v; v.push_back(25); foo(v); 

Or maybe:

 vector<int> v(1); v.at(0) = 25; foo(v); 

If you use v.at(n) instead of the [] operator, you will get an exception, not an undefined one.

+6
source

Source: https://habr.com/ru/post/922074/


All Articles