string or char* | SoloLearn: Learn to code for FREE!

+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/10/2019 6:34:54 PM

smh

17 Answers

New Answer

+11

smh Okay. no output is generally an indication of crash. But i think i got what is happening. s is empty string s[0] is null char so it's length is 0, and it's printing empty string. I'll update my previous comment.

+5

Emmanuel chiwala Fatima Maria Campelo Oliveira Itz Vincent يوسف حدو Guys if you do not have anything to contribute then at least don't spam someone's else thread !

+4

Because std::string operator [ ] is no-throw guarantee. Accessing an element out of bounds is undefined behaviour and may lead to segmentation faults

+3

'no output' is usually an indication of crash. s[2] = 'a' assigning char to string without allocating memory if you do something like char *s; s[2] = 'a'; your program will likely to crash.

+3

nAutAxH AhmAd No it is an object but it is dynamic in size and for C function compatibility it offers a conversion function to char*

+3

nAutAxH AhmAd sizeof(s) will give you size of string object

+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

Subscript operator on string object will not give you index out of range error. Try s.at(2) you will immediately get at exception.

+1

nAutAxH AhmAd If it doesn't crash you will get something. Check the size it will be 0

+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!

-1

Sorry, your code is wrong if you want to print string then you should have Char s[100] ; Now you can store any string.