Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print char array in c++

how can i print a char array such i initialize and then concatenate to another char array? Please 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 the output

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

basically i would like to see the output print

source: baby
return value: baby
pointer pass: baby
like image 418
Carlitos Overflow Avatar asked Nov 22 '11 15:11

Carlitos Overflow


People also ask

How do you print a char in C?

printf(char *format, arg1, arg2, …) This function prints the character on standard output and returns the number of character printed, the format is a string starting with % and ends with conversion character (like c, i, f, d, etc.).

How do you print a char function?

using printf() If we want to do a string output in C stored in memory and we want to output it as it is, then we can use the printf() function. This function, like scanf() uses the access specifier %s to output strings. The complete syntax for this method is: printf("%s", char *s);


1 Answers

You haven't initialized dest

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

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

Strings as char arrays must be delimited with 0. Otherwise there's no telling where they end. You could alternatively say that the string ends at its zeroth character by explicitly setting it to 0;

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

Or you could initialize your whole array with 0's

char dest[1024] = {};

And since your question is tagged C++ I cannot but note that in C++ we use std::strings which save you from a lot of headache. Operator + can be used to concatenate two std::strings

like image 116
Armen Tsirunyan Avatar answered Sep 21 '22 02:09

Armen Tsirunyan