2
#include<iostream> using namespace std; int main() { string str1 = "geeksforgeeks is for geeks"; string str2 = "geeksforgeeks is for geeks"; char ch1[100]; char ch2[100]; cout<<str1.size()<< endl << endl; str1.copy(ch1,23,0); str2.copy(ch2,24,0); cout << ch1 << endl << endl; cout << ch2 << endl << endl; return 0; } 

The length of string is 26, when I tried to copy more than 23 characters, it is showing weird behavior (printing random character in the last) Here is the output of the above program

26 geeksforgeeks is for ge geeksforgeeks is for gee£qí╜∙⌂ 
1

3 Answers 3

3

It's because you haven't set any '\0' (null) character to determine the end. That's why it's picking up garbage value.

you can do

#include<iostream> using namespace std; int main() { string str1 = "geeksforgeeks is for geeks"; string str2 = "geeksforgeeks is for geeks"; char ch1[100]; char ch2[100]; cout<<str1.size()<< endl << endl; str1.copy(ch1,23,0); str2.copy(ch2,24,0); ch1[23] = '\0'; ch2[24] = '\0'; cout << ch1 << endl << endl; cout << ch2 << endl << endl; return 0; } 
Sign up to request clarification or add additional context in comments.

Comments

2

It's because your char[]'s are uninitialized and you don't place a \0 at the end of the strings after the copy.

Another solution is to initialize the char[]'s at construction:

char ch1[100]{}; char ch2[100]{}; 

1 Comment

@Human That's undefined behavior in effect. The char[] probably has 24 bytes of \0 (even though it's uninitialized) for some reason out of your control.
2

You need to add null-terminator char by yourself; while std::string::copy doesn't do that.

E.g.

str1.copy(ch1,23,0); ch1[23] = '\0'; str2.copy(ch2,24,0); ch2[24] = '\0'; 

3 Comments

But why it works when we copy 23 characters or less? Why then the extra characters are not printed?
@Human The behavior of printing out a non null-terminated char* is undefined.
@tarunmali ch1 and ch2 are not initialized and contain indeterminate values for each index due to that. So one of the chars in ch1 and ch2 might be \0. In your example, ch1 might have a \0 after for ge, but that's not guaranteed. And even if it is a \0 it is still an indeterminate value that happens to be \0, but at the point, that value is read (when you are printing it) you encounter undefined behavior.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.