开发者

How to get a pointer to a member variable for memcpy

edited for clarification; why wont this work 开发者_StackOverflow中文版yet compile?

class Member{
public:
__int32 PublicInt;
}
Member x;
memcpy(&x.PublicInt,&ByteArray,sizeof(__int32));

is this not getting a pointer to the place where int is stored?


If your variable is

int Into;

...then its address is:

&Into

Note that what you get with an array reference is the address, so if ByteArray is really a byte array, I suspect you've just misplaced the & in your memcpy and that this is what you want:

memcpy(&Into, ByteArray, sizeof(__int32));

I'd also recommend doing this:

memcpy(&Into, ByteArray, sizeof(Into));

...in case you change its type later.


Here is a quick sample to help you understand:

#include<iostream>
#include<cstring>
class Myclass
{
    public:
        char str2[40];

};

int main()
{
   char str1[]="Sample string";
   Myclass obj;
   memcpy(&(obj.str2),str1,strlen(str1)+1);
   std::cout<<obj.str2;

   return 0;
}

Hth :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜