Copy struct C

1

How do I copy a pointer of type struct to C?

For example, to copy a simple struct is only struct1 = struct2 ; but when it comes to 2 pointers, when it does this, one points to the same location of the other, and then the same, the content changes in the original, wanted to know a way to make a copy of one pointer to another, content, not the memory address.

asked by anonymous 26.03.2015 / 15:05

1 answer

1

Assuming that each of the pointers points to a valid site

struct whatever {int a; int b; int c;};
struct whatever array[2];
struct whatever *p1, *p2;
p1 = array;       // p1 aponta para o primeiro elemento do array
p2 = array + 1;   // p2 aponta para o segundo elemento do array
array[0].a = array[0].b = array[0].c = 42;    // atribui valores a array[0] e *p1

*p2 = *p1;              // copia

printf("%d %d %d\n", array[1].a, array[1].b, array[1].c); // prints 42 42 42

If you need to allocate memory, the method is the same

struct whatever *p3 = NULL;
p3 = malloc(sizeof *p3);
if (p3) {
    *p3 = *p1;             // copia
    /* use p3 */
    free(p3);
} else /* error */;
    
26.03.2015 / 15:13