I'm trying to figure out why C does this. It's a very simple string concatenation code but I get very different outputs depending on what goes into strcat.
Can someone shed some light on this?
// With all declared variables
char * hello = "HELLO";
char * world = "WORLD";
char * space = " ";
char * say_hello(){
char * out = "";
strcat(out,hello);
strcat(out,space);
strcat(out,world);
return out;
}
main(){
puts(say_hello());
}
// outputs "HELLO WORLD"
// With all hello as declared variable
char * hello = "HELLO";
char * say_hello(){
char * out = "";
strcat(out,hello);
strcat(out," ");
strcat(out,"WORLD");
return out;
}
main(){
puts(say_hello());
}
// outputs "HELLOELLOLOELLO"
// With all hello and world as declared variable
char * hello = "HELLO";
char * world = "WORLD";
char * say_hello(){
char * out = "";
strcat(out,hello);
strcat(out," ");
strcat(out,world);
return out;
}
main(){
puts(say_hello());
}
// outputs "HELLOELLOWORLD"
// With all constants
char * say_hello(){
char * out = "";
strcat(out,"HELLO");
strcat(out," ");
strcat(out,"WORLD");
return out;
}
main(){
puts(say_hello());
}
// outputs "HELLO WORLD"