在结构指针中查找值的地址

Find address of value in a struct pointer

本文关键字:地址 查找 结构 指针      更新时间:2023-10-16

我有一个名为message的结构:

typedef unsigned char messageType;
struct message{
    message() : val(0), type(home),nDevice(0) {}
    messageType type;
    _int32 val;
    char nDevice;
};

我有一个指向该结构的指针:

message* reply;

我怎样才能得到 reply.val 的地址,以便我可以对它进行记忆?例如:

    memcpy(inBuf+2,address here,4);
memcpy(inBuf+2, &reply->val, sizeof(reply->val));

会这样做,因为->的优先级高于&地址。

如果您不确定运算符优先级,只需使用括号,可读性更重要:

memcpy(inBuf+2, &(reply->val), sizeof(reply->val));

感谢您@DyP的评论,请注意,使用sizeof(reply->val)比使用文字4更好。

尝试&(reply->val) .

但是,请注意,编译器可以向结构添加填充,这可能会破坏您的计划。

memcpy(&(reply->val), address, sizeof(address))