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

2
  • 1
    pointers need memory use malloc for f_add and char *f_add[20]; is not the right one to do concatenation Commented Feb 1, 2021 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. Commented Feb 1, 2021 at 12:49

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Your explanation is correct and helpful. Thanks
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;
}

1 Comment

I'm guessing they meant char f_add[20], and making it an array of pointers is accidental or a misunderstanding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.