Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   Matrices dinámicas (https://www.clubdelphi.com/foros/showthread.php?t=13665)

jplj 26-08-2004 14:15:10

Matrices dinámicas
 
La Guía del Lenguaje Object Pascal de Borland para Delphi 5 dice acerca de las matrices dinámicas (no obstante estoy trabajando con Delphi 7):
"Para crear una matriz en memoria, es necesario llamar a SetLength. ...

Para liberar la memoria asignada una matriz dinámica, basta tomar una variable que haga referencia a la matriz y asignarle el valor nil o pasarla a Finalize; ... "
Mi pregunta es si en el caso de llamar a SetLength para una matriz que ya tuviera asigana memoria, no libera primero la memoria asignada.

Es decir, el siguiente código -que funciona- ¿es correcto?:

Código Delphi [-]
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    Matriz: array of Integer;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
   SetLength(Matriz, 5);
   (Sender as TButton).Caption:= IntToStr(High(Matriz));
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
   SetLength(Matriz, 10);
   (Sender as TButton).Caption:= IntToStr(High(Matriz));
end;

o bien debería ser así:

Código Delphi [-]
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    Matriz: array of Integer;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin

   Matriz:= nil;

   SetLength(Matriz, 5);
   (Sender as TButton).Caption:= IntToStr(High(Matriz));
end;

procedure TForm1.Button2Click(Sender: TObject);
begin

   Matriz:= nil;

   SetLength(Matriz, 10);
   (Sender as TButton).Caption:= IntToStr(High(Matriz));
end;

Sirkius 26-08-2004 14:43:10

De la ayuda de Delphi, buscando SetLength:

Cita:

SetLength reallocates the string or array referenced by S to the given length
Y a mi entender, como dice que recoloca: pilla un hueco, copia lo existente y borra lo anterior.

Bye!

jplj 30-08-2004 08:57:38

Aunque tarde, gracias por la respuesta.


La franja horaria es GMT +2. Ahora son las 23:02:53.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi