开发者

How to get a pointer to a member variable for memcpy

开发者 https://www.devze.com 2023-03-23 14:29 出处:网络
edited for clarification; why wont this work 开发者_StackOverflow中文版yet compile? class Member{

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

精彩评论

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