I have been struggling with this. What I have found here on stackoverflow, and other places was to just do:
memcpy(&a, &b, sizeof(b));
But for me, that did not work. So I thought, I share what worked for me without any unexpected behavior.
In my case previous solutions did not work properly, e.g. the one in the question! (it copied about half of only the first element).
So in case, somebody needs a solution, that will give you correct results, here it is:
memcpy(a, b, n * sizeof(*b));
More detail:
int i, n = 50;
struct YourStruct *a, *b;
a = calloc(n, sizeof(*a));
b = malloc(n * sizeof(*b));
for (i = 0; i < n; ++i) {
// filling a
}
memcpy(b, a, n * sizeof(*a)); // <----- memcpy 'n' elements from 'a' to 'b'
if (a != NULL) free(a); // free 'a'
a = calloc(2*n, sizeof(*a)); // 'a' is size 2n now
memcpy(a, b, n * sizeof(*b)); // <------ memcpy back the 'n' elements from 'b' to 'a'
// do other stuff with 'a' (filling too)...
Some notes:
calloc() or the malloc() fails. Always check (!=NULL) the returned value from any memory allocation function (malloc, calloc, realloc) before using that value
aandbcame from