Assign one struct to another in C
First Look at this example :
The C code for a simple C program is given below
struct Foo {
char a;
int b;
double c;
} foo1, foo2;
void foo_assign(void)
{
foo1 = foo2;
}
int main(/*char *argv[],int argc*/)
{
foo_assign();
return 0;
}
The Equivalent ASM Code for foo_assign() is
00401050 <_foo_assign>:
401050: 55 push %ebp
401051: 89 e5 mov %esp,%ebp
401053: a1 20 20 40 00 mov 0x402020,%eax
401058: a3 30 20 40 00 mov %eax,0x402030
40105d: a1 24 20 40 00 mov 0x402024,%eax
401062: a3 34 20 40 00 mov %eax,0x402034
401067: a1 28 20 40 00 mov 0x402028,%eax
40106c: a3 38 20 40 00 mov %eax,0x402038
401071: a1 2c 20 40 00 mov 0x40202c,%eax
401076: a3 3c 20 40 00 mov %eax,0x40203c
40107b: 5d pop %ebp
40107c: c3 ret
As you can see that a assignment is simply replaced by a "mov" instruction in assembly, the assignment operator simply means moving data from one memory location to another memory location. The assignment will only do it for immediate members of a structures and will fail to copy when you have Complex datatypes in a structure. Here COMPLEX means that you cant have array of pointers ,pointing to lists.
An array of characters within a structure will itself not work on most compilers, this is because assignment will simply try to copy without even looking at the datatype to be of complex type.
Yes if the structure is of the same type. Think it as a memory copy.
Yes, assignment is supported for structs. However, there are problems:
struct S {
char * p;
};
struct S s1, s2;
s1.p = malloc(100);
s2 = s1;
Now the pointers of both structs point to the same block of memory - the compiler does not copy the pointed to data. It is now difficult to know which struct instance owns the data. This is why C++ invented the concept of user-definable assignment operators - you can write specific code to handle this case.