Clone a struct without copying the memory address

1

I need to copy struct problema1 to struct problema2 , but when doing the way you are in the program below, when I change the struct problema2 , you are also changing the struct problema1 . The way I did it by copying the reference, I wanted to copy without reference, but I do not know how to do it.

void __fastcall TForm1::Button1Click(TObject *Sender)
{

 struct Tproblem
   {
    TList *Lista;
    float x;
    };

  typedef struct Tproblem Problem;
  Problem *Problema1 ,*Problema2;
  int *x;
  Problema1 = new Problem;
  Problema1->Lista = new TList;
  for( int i = 0 ; i<10; i++)
    {
       x = new int ;
       *x = i;
       Problema1->Lista->Add(x) ;
     }



   Problema2 = new Problem;
    Problema2 = Problema1;// aki eu copia a estrutura


     for( int i = 0 ; i<Problema1->Lista->Count ;i++)
    {
      x = (int*)Problema1->Lista->Items[i];
      ListBox1->Items->Strings[i]=IntToStr(*x);
    
asked by anonymous 08.07.2016 / 18:08

1 answer

1

This code is copying the pointer, so the code has two variables pointing to the same object, so changing one changes the other. What you need to do is create a new object and point to it. This can be done with memcpy() . Something like this:

memcpy(Problema2, Problema1, sizeof(Problema1));

There are better ways to solve this, but then you would need to tinker with the whole code.

    
08.07.2016 / 19:40