Here I tried implementing strcat
function in C. Problem is that when I am printing the source string it is showing me "hyam"
not "shyam"
#include <stdio.h>
#include <string.h>
char *fun(char *target, const char *source) {
printf("%s\n", source);
int x = strlen(target);
while (*source != '\0') {
*(target + x++) = *source++;
}
*(target + x) = '\0';
return target;
}
int main() {
char target[] = "ram";
char source[] = "shyam";
fun(target, source);
printf("%s\n", target);
printf("%s", source);
return 0;
}
Here in last line of output hyam
is shown but it should be shyam
.
shyam
ramshyam
hyam
Your target
array is too small - it needs at least nine elements (the length of both strings plus a terminating zero).
Writing outside target
has undefined behaviour, but in practice, it looks like your arrays happen to be laid out end to end, like this:
|r|a|m|\0|s|h|y|a|m|\0|
^ ^
| |
target source
and then you concatenate, going past the end of target
into source
:
|r|a|m|s|h|y|a|m|\0|\0|
^ ^
| |
target source
which makes it look like an 's'
has disappeared.
(Note that this is undefined, so anything can happen. You can't rely on this behaviour, unless the documentation for your compiler says that it's fine and should do this. Which it most likely won't.)