• ### Popular Now

• 14
• 12
• 9
• 10
• 13

#### Archived

This topic is now archived and is closed to further replies.

# pointer stuff...again

This topic is 5996 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi I have a class like this: class A { public: int *num; public: A(){num = new int[1];} ~A(){if(num){delete[] num;}} }; And a little funktion: A* func(int &size) { size = 1; A *a; a = new A[size]; a[0].num[0] = 99; return a; } And a little program: int main() { int size; A *a,*a_tmp; a_tmp = new A[100]; a_tmp = func(size); a = new A[size]; memcpy(a,a_tmp,sizeof(A)*size); delete[] a_tmp; } This is just an example..as u can see its not very useful. The thing is am trying to clean up the memoryleaks in my program and I cant figure out how I can do this in a nice way... If I delete the temp pointer in this example I lose all data in pointer "a" too. So the question is how can i copy the data in one pointer to another like in the example and then delete the first one. Edited by - RZ on October 21, 2001 5:43:22 PM

##### Share on other sites
memcpy (and the compiler generated assignment operator) only creates a shallow copy of an object. This means that when you copy a_tmp[0] to a[0] the ''num''-pointers in both will point to the same memory location. You should create a deep copy. the easiest way is probably to define an assignment operator for your class, and avoid using memcpy to copy instances of it.

e.g. in the declaration of A you put something like:
  A& operator = (const A& a){ *num = *a.num; // num always points to 1 element in this example};

then instead of memcpy(a, a_tmp, sizeof(A)*size) you would write something like:
  for (int i = 0; i < size; ++i){ a[i] = a_tmp[i];};

This was a very simple example, and I probably forgot something. If you have a C++ book, look up ''operator overloading'' in it.