Less popular way to copy content of a structure

There is instance (let's call it p0) of structure, we create new instance (p1) of the same structure and want to copy content of fields from p0 to p1.

The simplest (IMHO also the best) way is to copy field by field. It's presented in following code (in case of p1 all fields are copied, in case of p2 only some).

/* output: 
foo (3.800000, 4.900000): #121212
bar (3.800000, 4.900000): #335566
*/
#include <stdlib.h>

struct Point {
    char desc[5];
    double x, y;
    char color[8];
};

int main() {
    struct Point p0 = {.desc = "foo", .x = 3.8, .y = 4.9, .color = "#121212"};

    struct Point p1;
    snprintf(p1.desc, sizeof(p1.desc), p0.desc);
    p1.x = p0.x;
    p1.y = p0.y;
    snprintf(p1.color, sizeof(p1.color), p0.color);
    printf("%s (%f, %f): %s\n", p1.desc, p1.x, p1.y, p1.color);

    struct Point p2;
    snprintf(p2.desc, sizeof(p2.desc), "bar");
    p2.x = p0.x;
    p2.y = p0.y;
    snprintf(p2.color, sizeof(p2.color), "#335566");
    printf("%s (%f, %f): %s\n", p2.desc, p2.x, p2.y, p2.color);

    return EXIT_SUCCESS;
}

The second way is use memcpy to copy content of memory allocated for p0 directly into p1. It's presented in next snippet.

/* output: 
foo (3.800000, 4.900000): #121212
bar (3.800000, 4.900000): #335566
*/
#include <stdlib.h>

struct Point {
    char desc[5];
    double x, y;
    char color[8];
};

int main() {
    struct Point p0 = {.desc = "foo", .x = 3.8, .y = 4.9, .color = "#121212"};

    struct Point p1;
    memcpy(&p1, &p0, sizeof(p0));
    printf("%s (%f, %f): %s\n", p1.desc, p1.x, p1.y, p1.color);

    struct Point p2;
    snprintf(p2.desc, sizeof(p2.desc), "bar");
    memcpy(&p2.x, &p0.x, sizeof(p2.x) + sizeof(p2.y));
    snprintf(p2.color, sizeof(p2.color), "#335566");
    printf("%s (%f, %f): %s\n", p2.desc, p2.x, p2.y, p2.color);

    return EXIT_SUCCESS;
}

For me the second way is really tricky ;)

0 commentaires:

Post a Comment