c++ - get out of range element from vector -


this question has answer here:

i doing tests , got around this:

#include <stdio.h>  #include <vector> #include <string>  class person{ public:     std::string name;      person(const char *name):         name(name){             printf("c-tor %s\n", name);         };      void print(){         printf(">> %s\n", name.c_str());     }; };  int main(){     std::vector<person> v;      v.push_back("ivan");     v.push_back("stoyan");     v.push_back("dragan");      v[10].print(); } 

if std::cout, crashes. if printf, prints:

c-tor ivan
c-tor stoyan
c-tor dragan
>> (null)

is working "correctly" chance , coincidence?

portable programs should never call function argument n out of range, since causes undefined behavior.

is working "correctly" chance , coincidence?

yes.

you have given reason quote

portable programs should never call function argument n out of range, since causes undefined behavior.

accessing v[10] when v.size() less 11 undefined behavior , program may crash or give unexpected (sometimes seeming correct) output.

cout may print std::string in different way accessing std::string::c_str , cout , printf may give different results.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -