+ 2
string or char*
In my code, why using string doesn't make an exeption and work like char*? https://code.sololearn.com/cUbLha0LrxeN/?ref=app
10 Antworten
+ 4
Because std::string operator [ ] is no-throw guarantee.
Accessing an element out of bounds is undefined behaviour and may lead to segmentation faults
+ 2
~ swim ~ Are strings dynamic char arrays?
+ 2
Thanks!
+ 2
Check this out,
int main() {
string s;
s[2]='a';
cout<<s[2]<<endl;
}
According to what you said, it shouldn't print anything as the first character is null.
But if you print it by its index, it has output.
+ 2
Oh, I see. Thanks for clarification.
+ 1
But i interested where i didn't get index out of range or segmentation fault as exception!
+ 1
int main() {
string s;
s[2] = 'a';
cout << s[2] << endl;
cout << sizeof(s) << endl;
}
Maybe not, I am getting 32 🤔
+ 1
But yes, the length function is giving me 0 output.
0
I have an empty string as output in my system!
- 2
Sorry, your code is wrong if you want to print string then you should have
Char s[100] ;
Now you can store any string.