Copy struct C

Asked

Viewed 3,017 times

1

How do I copy a pointer of the type struct in C?

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


  • *pointer 1 = *pointer 2;

1 answer

1


Assuming 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 memory needs to be allocated, the method is the same

struct whatever *p3 = NULL;
p3 = malloc(sizeof *p3);
if (p3) {
    *p3 = *p1;             // copia
    /* use p3 */
    free(p3);
} else /* error */;
  • 1

    *p3 = *p1 ; free(p3) nothing is missing?

  • I was thinking the same @Jjoao

  • 1

    *p3 = *p1; /* use p3 */; free(p3); ... ready! I don’t see what’s missing.

  • (When I was malloc; atritui; free Misleading: the use has to be before the clear free) so it is clearer. + 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.