Assignment
The following assignment of a struct to another struct does what one might expect. It is not necessary to use memcpy
to make a duplicate of a struct type. The memory is already given and zeroed by just declaring a variable of that type regardless of member initialization. This should not be confused with the requirement of memory management when dealing with a pointer to a struct.
#include
/* Define a type point to be a struct with integer members x, y */
typedef struct { int x; int y;
} point;
int main(void) {
/* Define a variable p of type point, and initialize all its members inline! */ point p = {1,2};
/* Define a variable q of type point. Members are initialized with the defaults for their derivative types such as 0. */ point q;
/* Assign the value of p to q, copies the member values from p into q. */ q = p;
/* Change the member x of q to have the value of 2 */ q.x = 2;
/* Demonstrate we have a copy and that they are now different. */ if (p.x != q.x) printf("The members are not equal! %d != %d", p.x, q.x); return 0;
}