1

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.

3
  • sizeof(b) will tell you the size of the pointer, not the size of the memory block that b points to. So, your line of code will only copy 4 or 8 bytes depending on the system architecture (32 or 64 bit). You need to pass the 3rd parameter to memcpy to really say how much memory to copy. Commented Dec 4, 2015 at 22:51
  • 1
    yes, I have realized/understood/read that by now :), but for some reason this is what I find as accepted solution for questions :/. Commented Dec 4, 2015 at 22:54
  • You need to show where a and b came from Commented Dec 4, 2015 at 23:57

2 Answers 2

2

Assume you have:

#define N 42
struct struct_name *a = malloc(sizeof *a * N);  // allocate N objects
struct struct_name *b = malloc(sizeof *b * N);  // allocate N objects

then the correct memcpy call to copy the array of structure objects is:

memcpy(a, b, sizeof *a * N);
Sign up to request clarification or add additional context in comments.

Comments

1

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:

  • I used calloc for a, because in the '// filling a' part I was doing operations that required initialized data.
  • I could have used realloc as well.
  • I was kind of doing a dynamically growing array (with doubling size -> log(n)), but here I simplified it.
  • You should check, if memory allocation is successful or not (a,b NULL or not). But here, I removed those checks for simplification.

3 Comments

Thanks for pointing it out, it was malloc before, and I just copied it. That caused the typo.
the posted code can result in a seg fault event if either the calloc() or the malloc() fails. Always check (!=NULL) the returned value from any memory allocation function (malloc, calloc, realloc) before using that value
Thanks for pointing it out, but this is just a simplified version, which tries to show usage of memcpy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.