简体   繁体   English

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

[英]Find address of value in a struct pointer

I have a struct called message: 我有一个名为message的结构:

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

And i have a pointer to that struct: 我有一个指向该结构的指针:

message* reply;

How can I get the address of reply.val so I can memcpy to it? 我如何获得reply.val的地址,以便能够记忆呢? eg: 例如:

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

will do because the precedence of -> is higher than address-of & . 之所以会这样做是因为->的优先级高于&地址。

If you are not sure about operator precedence, just use parenthesis, readability is more important: 如果不确定运算符的优先级,只需使用括号,可读性就更重要:

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

Thanks for @DyP's comment, note that it's better to use sizeof(reply->val) than the literal 4 . 感谢@DyP的评论,请注意,使用sizeof(reply->val)比文字4更好。

Try &(reply->val) . 尝试&(reply->val)

Be aware that the compiler can add padding to structs which will potentially ruin your plan, however. 请注意,编译器可以向结构中添加填充,但这可能会破坏您的计划。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM