1

I arrived at two different cases but was not able to arrive at a conclusion that what was actually happening inside. Can anyone please explain?

CASE 1:

#include<iostream>
using namespace std;
int main() {
string my_string = "This is a sam\0ple text"; //check the \0
cout << my_string;
return 0;
}

OUTPUT:

This is a sam

CASE 2:

#include<iostream>
using namespace std;
int main() {
string my_string = "This is a sample text"; 
my_string[13]='\0';
cout << my_string;
return 0;
}

OUTPUT:

This is a sam le text

I thought these two cases are similar and hence the output should come out to be the same but actually this is what was happening. Please explain.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • How is `my_string` declared? Please, refer to [repro]. – Enlico May 25 '21 at 05:05
  • 9
    `std::string` can contain nul (`\0`) bytes - they are _not_ nul terminated but instead have a certain length and can contain any character, **but** when you initialize with a string literal (case 1) the literal is a c-style null-terminated string - so it copies up to the first nul (`\0`) byte. – davidbak May 25 '21 at 05:09
  • 3
    And that means to correctly answer this question we need to know if `std::string` is being used. – user4581301 May 25 '21 at 05:13

0 Answers0