cmemcpyoffsetof

Copying part of a struct using memcpy and offsetof


I'd like to copy part of a struct starting from a certain element forward by combining the offsetof macro and memcpy, as shown below:

#include <stdio.h>
#include <string.h>
#include <stddef.h>

struct test {

  int x, y, z;
};

int main() {

  struct test a = { 1, 2, 3 };
  struct test b = { 4, 5, 6 };

  const size_t yOffset = offsetof(struct test, y);

  memcpy(&b + yOffset, &a + yOffset, sizeof(struct test) - yOffset);

  printf("%d ", b.x);
  printf("%d ", b.y);
  printf("%d", b.z);

  return 0;
}

I expected this to output 4 2 3 but it actually outputs 4 5 6 as if no copying had taken place. What did I get wrong?


Solution

  • You're doing pointer arithmetic on a pointer of wrong type, and were writing to some random memory on stack.

    Since you want to calculate byte offsets, you must use a pointer to a character type. So for example

    memcpy((char *)&b + yOffset, 
           (const char *)&a + yOffset, 
           sizeof(struct test) - yOffset);