I am more confused with structures. There are many ways to copy a structure.
struct complex
{
int real;
int imaginary;
};
Assume c1 is complex structure v
I you change the order of fields in the following way:
struct complex
{
int imaginary;
int real;
);
Then memcpy(&c1.real, &c2->real, sizeof(struct complex))
will try to copy fields starting from real
and as the number of bytes you are trying to copy is the size of the whole structure it will access memory after the structure thus causing invalid memory access in some cases and in some cases it will does not produce any error. But the result of this operation is not what you expected. For ones, it will not copy the field imaginary
.
In case of you need to copy part of the structure - this is the way to do it:
memcpy(&c1.real, &c2->real, sizeof(struct complex) - offsetof(struct complex, real));
Where offsetof
is a macro declared like here.