Need immediate help on storing a pointer in a char array

Following is the pseudo code I have created.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<iostream>
using namespace std;

class sample
{
 public:
  int value;
  unsigned char p;
};

class timer
{
 public:
 char arr[200];
};


int main()
{
 sample* ptr=new sample;

 ptr->value = 5;
 ptr->p = 'c';

 cout<<"address of ptr "<<&ptr<<endl;
 cout<<endl;


 /*
  timer* time;
 memset(&time,0,sizeof(timer)); 
  memcpy(time->arr,ptr,sizeof(sample));
  */

 timer time;
 memset(&time,0,sizeof(timer));
 memcpy(time.arr,ptr,sizeof(ptr));

 return 0;


}

Program doesn't give segmentation fault but I am not sure whether the method I have used is right. Also, I assume the pointer location of ptr is stored in first 4 or 8 (for 64 bits) bytes of "arr".

If the method is right, then
1. How do I make sure the values are correctly copied? I mean how do I print out the actual values?
2. While retrieving data from the timer class, how I do get it back? Using same method, that is, find the pointer location first and then values or something else needs to be done?

Thanks in advance.
Also, I assume the pointer location of ptr is stored in first 4 or 8 (for 64 bits) bytes of "arr".
Nope. The first sizeof(ptr) bytes of what ptr points to is stored in the array (which is likely the content of value (i.e. 5))

This memcpy(time.arr,ptr,sizeof(*ptr)); copies the content of ptr
This
1
2
sample* ptr1=new sample;
 memcpy(ptr1,time.arr,sizeof(sample));
copies it back to a new instance of sample

It's is certainly not recommended to copy a class type like that.
memcpy(time.arr,&ptr,sizeof(ptr)); should work
Topic archived. No new replies allowed.