c++ - Copying the address of an object into a buffer and retrieving it -


i copy address of object buffer , typecast @ other point. unable it. sample code given below.

 #include <iostream> #include <cstring>  class myclass {  public:     myclass(const int & i)     {         id = i;     }       ~myclass()     {      }       void print() const     {         std::cout<<" id: "<<id<<std::endl;                }  private:     int id;  };    int main() {   myclass *myclass = new myclass(10); std::cout<<"myclass: "<<myclass<<std::endl;  myclass->print();  // need copy address buffer , retrieve later char tmp[128]; //  std::vector tmp(sizeof(myclass); // preferably, may use instead of previous line, , use std::copy instead of memcpy  memcpy(tmp, myclass, sizeof(myclass));   // retreiving pointer    myclass* myclassptr = (myclass*) tmp; std::cout<<"myclassptr: "<<myclassptr<<std::endl; myclassptr->print();  return 0; } 

in fact, pointers gives different values, source of problem. doing wrong here?

you copying (a pointer-sized part of) object itself, not pointer. should do:

memcpy(tmp, &myclass, sizeof(myclass)); 

and back:

myclass *ptr; memcpy(&ptr, tmp, sizeof(ptr)); 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -