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?
What is it you actually want to do?
With
unless you omitted some initialisation in between, you get undefined behaviour. The contents of the
malloced memory is unspecified, so when*bufis interpreted as avoid*inmemcpy, 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
bufto contain the two pointers, after themallocis the simplest and cleanest solution, but
would also be valid (also with
&buf[1]instead ofbuf + 1.If you want to concatenate the strings
aandbpoint to, you’re following a completely wrong approach. You’d need achar*pointing to a sufficiently large area to hold the result (including the 0-terminator) and the simplest way would be usingstrcat.