#include <stdio.h>
#include <stdint.h>
struct s1
{
uint8_t a;
uint16_t b;
uint8_t c;
};
struct s2
{
uint8_t d;
uint8_t e;
};
int main()
{
struct s1 *d1;
struct s2 *d2;
d1->a = 1;
d1->b = 2;
d1->c = 3;
d2->d =4;
d2->e =5;
&d1->b = d2;
return 0;
}
Why doesn't &d1->b = d2; work? b is 32 bit and the struct s2 is also 32 bit? As we are just assigning the address.
If that line is changed to d1 = (void *)d2; It works without an error.
CodePudding user response:
First. The pointer d1 and d2 are not initialized. Using this pointer invokes Undefined Behavior. To fix it I suggest making the the actual object with automatic storage.
struct s1 d1;
struct s2 d2;
You cannot assign d2 to d1.b because the types do not match. struct s2 and uint16_t are not compatible. To do this type of type punning use memcpy().
memcpy(&d1.b, &d2, sizeof d2);
