[Overview][Constants][Types][Classes][Procedures and functions][Variables][Index] | Reference for unit 'System' (#rtl)

# SetLength

Set length of a string or dynamic array.

## Declaration

Source position: system.fpd line 82

`procedure SetLength(`
`var S: AStringType;`
`Len: SizeInt`
`); procedure SetLength(`
`var A: DynArrayType;`
`Len: SizeInt`
`);`

## Description

SetLength for strings sets the length of the string S to Len. S can be an ansistring, a short string or a widestring. For ShortStrings, Len can maximally be 255. For AnsiStrings it can have any value. For AnsiString strings, SetLength must be used to set the length of the string.

In the case of a dynamic array A, SetLength sets the number of elements. The elements are numbered from index 0, so the count runs from 0 to Len-1. If Zero is specified, the array is cleared and removed from memory.

In case the length is set to a smaller length than the current one, the elements 0-(Len-1) (or characters 1-Len in case of a string) are kept. The elements that fall outside the new length are finalized if the array element is a managed type.

In case the length is set to a larger length than the current one, the new elements are zeroed out for a dynamic array. For a string, the string is zero-terminated at the correct length.

Note that SetLength is governed by the Copy-On-Write principle for strings and dynamic arrays: the reference count after a call to SetLength will be 1 (except when the length is zero, then the array is removed from memory).

For multi-dimensional arrays, SetLength can be used to specify all dimensions at once:

    Var
      arr : Array of Array of Integer;

    begin
      SetLength(arr, 10, 20);
    end;

This will create a dynamic array with 10 elements, where each element in itself is a dynamic array of 20 elements. SetLength will of course always create "rectangular" arrays: all elements will have the same size.

    Var
      arr : Array of Integer;

    begin
      SetLength(arr,0);
    end;

After this, arr is Nil.

## Errors

None.

## See also

Length |  | Returns length of a string or array.

## Example

    Program Example85;

    { Program to demonstrate the SetLength function. }

    Var S : String;

    begin
      Setlength(S,100);
      FillChar(S[1],100,#32);
      Writeln ('"',S,'"');
    end.