error: lvalue required as left operand of assignment for &d1->b = d2; but no error for d1 = (void *)d2;

error: lvalue required as left operand of assignment for &d1->b = d2; but no error for d1 = (void *)d2;

#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;
}

为什么 &d1->b = d2; 不起作用? b 是 32 位而 struct s2 也是 32 位?因为我们只是分配地址。

如果将该行更改为 d1 = (void *)d2; 它可以正常工作。

首先。指针 d1d2 未初始化。使用此指针调用未定义的行为。要修复它,我建议使实际对象具有自动存储功能。

struct s1 d1;
struct s2 d2;

您不能将 d2 分配给 d1.b,因为类型不匹配。 struct s2uint16_t 不兼容。要进行这种类型的双关语,请使用 memcpy().

memcpy(&d1.b, &d2, sizeof d2);