+ 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

10th Oct 2019, 6:34 PM
SMH
SMH - avatar
17 Réponses
+ 4
Because std::string operator [ ] is no-throw guarantee. Accessing an element out of bounds is undefined behaviour and may lead to segmentation faults
10th Oct 2019, 8:04 PM
AZTECCO
AZTECCO - avatar
+ 2
~ swim ~ Are strings dynamic char arrays?
10th Oct 2019, 6:48 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 2
Thanks!
10th Oct 2019, 6:58 PM
SMH
SMH - avatar
+ 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.
10th Oct 2019, 7:03 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 2
Oh, I see. Thanks for clarification.
10th Oct 2019, 7:11 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 1
But i interested where i didn't get index out of range or segmentation fault as exception!
10th Oct 2019, 6:59 PM
SMH
SMH - avatar
+ 1
int main() { string s; s[2] = 'a'; cout << s[2] << endl; cout << sizeof(s) << endl; } Maybe not, I am getting 32 🤔
10th Oct 2019, 7:08 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 1
But yes, the length function is giving me 0 output.
10th Oct 2019, 7:09 PM
blACk sh4d0w
blACk sh4d0w - avatar
0
I have an empty string as output in my system!
10th Oct 2019, 6:49 PM
SMH
SMH - avatar
- 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.
12th Oct 2019, 3:55 PM
Pushpendra Singh
Pushpendra Singh - avatar