2

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;
}

Hemjal
  • 130
  • 2
  • 7
  • 1
    pointers need memory use `malloc` for `f_add` and `char *f_add[20];` is not the right one to do concatenation – IrAM Feb 01 '21 at 10:54
  • 1
    Why `memcpy` and not `strcpy` & `strcat`? `strcpy( f_add, var1 ); strcat( f_add, var2 );` (and define `f_add` correctly). PS: You problem (one of all) is this `+8` - you need `+7` because 8 is beyond the zero, i.e. second string is ignored. – i486 Feb 01 '21 at 12:49

2 Answers2

2

char *f_add[20]; defines an array of two pointers to char. You probably want a simple array of 20 char:

char f_add[20];

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:

memcpy(f_add+7, var2, strlen(var2)+1);

You could also use memcpy(f_add + strlen(f_add), var2, strlen(var2)+1);, although that is effectively what strcpy(f_add, var2) does.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
0

Array of pointers is only holding the address (reference) of the string literals. And your code makes no sense at all.

int main(void)
{
    char *var1 = "my name";
    char *var2= "is khan";
    char *f_add[20];

    f_add[0] = var1;
    f_add[1] = var2;
    printf("%s\n%s", f_add[0], f_add[1]);
    return 0;
}

or you need to allocate the space for the strings

int main(void)
{
    char *var1 = "my name";
    char *var2= "is khan";
    char *f_add[20];

    f_add[0] = malloc(strlen(var1) + 1);
    f_add[1] = malloc(strlen(var2) + 1);

    memcpy(f_add[0],var1, strlen(var1)+1);
    memcpy(f_add[1],var2, strlen(var2)+1);

    printf("%s\n%s", f_add[0], f_add[1]);
    return 0;
}
0___________
  • 60,014
  • 4
  • 34
  • 74
  • I'm guessing they meant `char f_add[20]`, and making it an array of pointers is accidental or a misunderstanding. – Hasturkun Feb 01 '21 at 11:01