How to print char array in C ++

how can I print a char array that is initialized to i and then concatenated with another char array? See code below

int main () { char dest[1020]; char source[7]="baby"; cout <<"source: " <<source <<endl; cout <<"return value: "<<strcat(dest, source) <<endl; cout << "pointer pass: "<<dest <<endl; return 0; } 

this is a conclusion

 source: baby return value: v    baby pointer pass: v    baby 

Basically I would like to see print output

 source: baby return value: baby pointer pass: baby 
+7
source share
4 answers

You did not initialize dest

 char dest[1020] = ""; //should fix it 

You just got lucky it happened that the 6th (random) value in dest was 0 . If it were the 1000th character, your return value would be much longer. If it is greater than 1024, you will get undefined behavior.

Strings as char arrays must be separated by the character 0 . Otherwise, it is not reported where they end. You can also say that the string ends with a null character, explicitly setting it to 0;

 char dest[1020]; dest[0] = 0; 

Or you can initialize the whole array with 0

 char dest[1024] = {}; 

And since your question is marked by C++ , I cannot help but note that in C ++ we use std::string , which saves you a big headache. The + operator can be used to concatenate two std::string s

+9
source

Do not use char[] . If you write:

 std::string dest; std::string source( "baby" ) // ... dest += source; 

you will not have a problem. (Actually, your problem is that strcat requires as the first argument a string with the terminated '\0' and you give it random data. This behavior is undefined.)

+4
source

the dest array is not initialized. therefore strcat tries to add source to the end of dest , which is determined by the strcat '\0' character, but it is undefined where an uninitialized array can end ... (if that happens at all) ..)

so that you end up typing more or less random characters until the random character '\0' appears ...

+1
source

try it

 #include <iostream> using namespace std; int main() { char dest[1020]; memset (dest, 0, sizeof(dest)); char source[7] = "baby"; cout << "Source: " << source << endl; cout << "return value: " << strcat_s(dest, source) << endl; cout << "pointer pass: " << dest << endl; getchar(); return 0; } 

Used VS 2010 Express. clear memory using memset , as soon as you declare dest, it is safer. Also, if you use VC ++, use strcat_s () instead of strcat ().

0
source

All Articles