Are arrangements based on 0 or 1 on Delphi / Pascal?

1

I want to make an arrangement in Delphi. I found a solution with this code:

var arr: array of String;

Every time I add something, I do it this way:

var
  Form1: TForm1;
  var arr : array of String;

procedure TForm1.Button1Click(Sender: TObject);
var 
  aux :string;
  len:integer;
begin
  len := Length(arr) + 1;
  SetLength(arr, len);
  arr[len-1] := 'abc' + IntToStr(len);
  Button1.Caption := arr[len-1]; // just to writeout something
end;

I'm a C ++ programmer and I do not know anything about Pascal. I have always heard that the indexes in Pascal start at 1 and not at 0. In the procedure above, I do arr[len-1] as if the index started at 0, and it works!.

    
asked by jachguate 29.08.2016 в 18:11
source

1 answer

2

In Delphi (or in Pascal in general), there are different types of fixes, and the answer depends on the type of fix in use. In your case, you are using dynamic arrays:

Dynamic Arrays

Indices based on 0

var
  a: array of Integer;
begin
  SetLength(a, 500);
  a[0] := 0;   //primer elemento 
  a[499] := 1; //último elemento

Static Arrays

They may have arbitrary indexes

var
  i: Integer;
  b: array [50..100] of Integer;
  c: array[-10..10] of Integer; 
begin
  for i := 50 to 100 do b[i] := i * i;

  //Nota la declaración del índice que inicia en negativo
  for i := -10 to 10 do c[i] := i * i;

Character strings

Traditional compiler (win32 / win64)

Indexes start at 1

var
  c: String;
begin
  c := 'Zap!';
  c[1] := 'W';
  ShowMessage(c); /// Muestra 'Wap!'

NEXTGEN Compiler (Android, iOS, OSX, Linux)

Indexes start at 1

var
  c: String;
begin
  c := 'Zap!';
  c[0] := 'W';
  ShowMessage(c); /// Muestra 'Wap!'

Auxiliary functions

When working with fixes, in any case you can use the functions Low() and High() to determine the limits of the index of an array.

var
  arr1: array[-10..20] of Integer;
  arr2: array of Integer;
  C: string;
  I: Integer;
begin
  for I := Low(arr1) to High(arr1) do
    //algo
  for I := Low(arr2) to High(arr2) do
    //algo más
  for I := Low(C) to High(C) do
    //algo más aún

Delphi also has classes to handle generic TArray<T> and other generic collections that you may find useful.

    
answered by 29.08.2016 / 18:11
source