Not sure if I called my problem correctly, but oh well.

const len = 100; TButton* Btn[len]; void CreateBtn(int amount) { for (int i = 0; i < amount; i++) { Btn[i] = new TButton(Form1); Btn[i]->Parent = Form1; //--- } } void __fastcall TForm1::FormCreate(TObject *Sender) { CreateBtn(5); } void __fastcall TForm1::Button1Click(TObject *Sender) { for (int i = 0; i < len; i++) { delete Btn[i]; } CreateBtn(4); } 

Left only the most necessary. Now I will explain the problem with the array.

First, I add 5 elements to the Button1Click array, then at the Button1Click event Button1Click array is cleared and 5 elements are entered into it again. It works.

If at the Button1Click event I bring not 5, but less (4, as in the code above), then after the next press (that is, one click) on Button1 I get an Access violation error at address 00000000, Read of address 00000000

It turns out if for the first time I entered a certain number of elements in FromCreate , then I can no longer bring less. How to solve it?

  • After delete Btn[i]; the pointer should be zeroed out, otherwise at the next iteration there will be an attempt to re-delete pointer # 5, which has already been deleted, leading to unspecified behavior. - VTT
  • and even better use smart pointers - AR Hovsepyan
  • const len = 100; - where is the type ??? - AnT
  • Ahaha I forgot to type ukat, but it does not give an error - RealPeha

1 answer 1

1) Use a dynamic (real, specified via SetLength) array, list or vector (the latter are better suited by semantics)
2) FreeAndNil to provide a null pointer after deletion (does not solve all problems)
3) Use the variable RealCount, which is set to the value of amount

  • I chose for myself the third option, as the most simple. Everything Works, Thanks - RealPeha