Hemjal
Hemjal

Reputation: 310

C Pointer array is not working with memcpy

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

Upvotes: 2

Views: 139

Answers (2)

Eric Postpischil
Eric Postpischil

Reputation: 223795

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.

Upvotes: 2

0___________
0___________

Reputation: 67835

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

Upvotes: 0

Related Questions