Why an empty string can output an index element 0 in C ++

#include<iostream> #include<string> using std::string; using std::cout; using std::endl; int main() { string s; cout << s.size() << endl; cout << s[0] << endl; //output empty line return 0; } 

How s is an empty string, why can it have an element s [0] ? In my opinion, it should get a runtime error. Is this an agreement or something else?

+6
source share
1 answer

There is a special rule, access to s[n] , where n is the length of s . The result is a null character (that is, a value that is the result of initializing a character type value) and attempting to change it causes undefined behavior.

+4
source

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


All Articles