Set length

A função SetLength é uma função nativa da linguagem Pascal/Delphi, usada para definir ou alterar o tamanho de arrays dinâmicos e strings. Ela aloca ou realoca memória conforme necessário


Sintaxe

procedure SetLength(var A: array of Tipo; NewLength: Integer);
procedure SetLength(var A: string; NewLength: Integer);
procedure SetLength(var A: array of array of Tipo; Dim1, Dim2: Integer);

Parâmetros

Nome Tipo Descrição
A Variável array dinâmico ou string) cujo tamanho será ajustado
NewLength Novo tamanho desejado para o array ou string
Dim1, Dim2 No caso de arrays multidimensionais, define o tamanho de cada dimensão.

Exemplos:

1. Uso com arrays

var
   Nomes: array of String;
 begin
   // Ajustando o tamanho do array para 3 elementos
   SetLength(Nomes, 3);
 
   // Atribuindo valores aos elementos do array
   Nomes[0] := 'Alice';
   Nomes[1] := 'Bob';
   Nomes[2] := 'Charlie';
   ShowMessage('Nome 1: ' + Nomes[0]);
 end.


2. Uso com Strings

var
  Texto: string;
begin
  // Definindo uma string com 10 caracteres vazios
  SetLength(Texto, 10);
  
  // Atribuindo um valor à string
  Texto := 'Delphi';
  
  ShowMessage('Texto: ' + Texto);
end. 

3. Arrays Multidimensionais

var

 Matriz: array of array of Integer;

begin

 // Criando uma matriz 5x5
 SetLength(Matriz, 5, 5);
 // Atribuindo valores
 Matriz[0][0] := 10;
 Matriz[4][4] := 99;
 ShowMessage('Elemento [0,0]: ' + IntToStr(Matriz[0][0]));

end.