I would like to concatenate two string with memcpy. But next memcpy is not working. My expected output is "my name is khan".
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *var1 = "my name";
char *var2= "is khan";
char *f_add[20];
memcpy(f_add,var1, strlen(var1)+1);
memcpy(f_add+8,var2, strlen(var2)+1);
printf("%s", f_add);
return 0;
}
char *f_add[20];
defines an array of two pointers tochar
. You probably want a simple array of 20char
:Then you need to copy to the right place. Copying to
f_add+8
starts writing after the null byte that marks the end of the first string, because that string, “my name” has seven non-null characters and one null terminator. So you need to start the copy on the null character:You could also use
memcpy(f_add + strlen(f_add), var2, strlen(var2)+1);
, although that is effectively whatstrcpy(f_add, var2)
does.