0
I’m trying to create a Delphi database to register and save to a 3 basic variables dynamic array. To do this, I created a global dynamic array named Pedidos
, one Record
Tpedidoitem with id, name and value, and other Record
Ordered that receives the record
Tpedidoitem:
TPedidoItem= record
id: Integer;
nome: string;
valor: Real;
end;
TPedido= record
pedido: TPedidoItem
end;
How I declared the dynamic array:
private
Pedidos: array of TPedidoItem;
After that, I call a registration process that saves instances of values, adds one more space in the array Pedidos
,saves this data in the array and then displays the values in a label
screen:
procedure TForm1.CadastrarClick(Sender: TObject);
var
pedido: TPedidoItem;
tamanho: Integer;
begin
tamanho:= Length(Pedidos)+ 1;
SetLength(Pedidos,tamanho);
with pedido do
begin
id:= StrToInt(Ed3Num1.Text);
nome:= Ed3Text1.Text;
valor:= StrToInt(Ed3Num2.Text);
end;
Pedidos[tamanho].id:= pedido.id;
Pedidos[tamanho].nome:= pedido.nome;
Pedidos[tamanho].valor:= pedido.valor;
Lista3.Caption:=Lista3.Caption +'Id: '+ IntToStr(Pedidos[tamanho].id)
+ ' | Nome: '+ Pedidos[tamanho].nome
+ ' | Valor: ' + FloatToStr(Pedidos[tamanho].valor)+#13;
end;
I tried to debug to see what I was doing wrong, however, the program performs all the tasks until the end without showing the error, the error only appears after having reached the end;
process. You know what I’m doing wrong? Something tells me it might be the way I’m trying to save the data in the dynamic array, but I don’t know how I should save it.
Progress(more or less)
I discovered the problem, the program tried to save the data in a position of the array that did not exist. I managed to solve the problem in a completely inefficient way:
tamanho:= tamanho - 1;
Pedidos[tamanho].id:= pedido.id;
Pedidos[tamanho].nome:= pedido.nome;
Pedidos[tamanho].valor:= pedido.valor;
Lista3.Caption:=Lista3.Caption +'Id: '+ IntToStr(Pedidos[tamanho].id)
+ ' | Nome: '+ Pedidos[tamanho].nome
tamanho:= tamanho + 1;
Considering the above code, what would be the best way to register the data with this dynamic array
In case I used one
for i:=o to vIdx
, to then do a check with the array id, could bring this problem of Eaccessviolation? Or would it work normally?– riki481
would work normally, because the
vIdx
starts at 0 and goes to greater of the array, the correct would befor i := Low(Pedidos) to High(Pedidos) do
– Junior Moreira