Search code examples
cmemcpy

Copy two char* to **buff with memcpy - C language


I got two char pointer:

char *a="A";
char *b="B";

And a pointer to pointer buffer:

char **buf = malloc(sizeof(char*)*2);

And I want use memcpy to copy two variables to buf:

memcpy(*buf, &a, sizeof(char*));
memcpy(*buf, &b, sizeof(char*));

but it replace first variable..

how can I copy two?


Solution

  • What is it you actually want to do?

    With

    char **buf = malloc(sizeof(char*)*2);
    
    memcpy(*buf, &a, sizeof(char*));
    memcpy(*buf, &b, sizeof(char*));
    

    unless you omitted some initialisation in between, you get undefined behaviour. The contents of the malloced memory is unspecified, so when *buf is interpreted as a void* in memcpy, that almost certainly doesn't yield a valid pointer, and the probability that it is a null pointer is not negligible.

    If you just want buf to contain the two pointers, after the malloc

    buf[0] = a;
    buf[1] = b;
    

    is the simplest and cleanest solution, but

    memcpy(buf, &a, sizeof a);
    memcpy(buf + 1, &b sizeof b);
    

    would also be valid (also with &buf[1] instead of buf + 1.

    If you want to concatenate the strings a and b point to, you're following a completely wrong approach. You'd need a char* pointing to a sufficiently large area to hold the result (including the 0-terminator) and the simplest way would be using strcat.