Reputation: 107
I have this simple code in C++:
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
s[0]='A';
cout << "s is: " << s << endl
<< "s[0] is: " << s[0] << endl;
}
why is s empty but s[0] has value of 'A'? can C++ strings be assigned values to its elements directly via index? Thanks!
Upvotes: 0
Views: 635
Reputation: 596121
why is s empty
Because you default-constructed it, so it is initially empty, and you did not do anything to allocate memory for its character storage.
but s[0] has value of 'A'?
It does not. You are assigning 'A'
to memory that has not been allocated yet.
can C++ strings be assigned values to its elements directly via index?
Yes, but only for valid indexes in the range of 0..size()-1
when size()
is > 0. In your example, index 0 is not valid because s.size()
is 0.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
s.resize(1); // <-- add this!
s[0]='A';
cout << "s is: " << s << endl
<< "s[0] is: " << s[0] << endl;
}
Upvotes: 1
Reputation: 16453
This is undefined behavior. The string s
is empty. Until C++11 you can't access s[0]
. Since C++11 you can read s[0]
but you can't write it.
You could resize the string with
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
s.resize(1);
s[0]='A';
cout << "s is: " << s << endl
<< "s[0] is: " << s[0] << endl;
}
Read https://en.cppreference.com/w/cpp/string/basic_string/operator_at
Upvotes: 4