Search code examples
memory-managementpascal

Can I define my own string type in Pascal?


I’ve read you cannot dynamically allocate an array in Pascal, but I’m also thinking of implementing a string struct.

In C, I would go about it by creating a struct containing a pointer to an array of chars (containing the characters), a length integer, and a size one. I would then malloc the char * and realloc it when it needs to be resized.

typedef struct {
    size_t size;
    size_t length;
    char* contents;
} String;

Can this be done in (ISO) Pascal? I don’t want to use a built‐in Pascal dynamic array because it defeats the purpose of making my own string type.

From the comments, it seems like ISO Pascal (both Standard and Extended) doesn’t support such things. Is it possible in Free Pascal?


Solution

  • In Free Pascal it can be implemented similar to the mentioned C approach:

    type
    TMyString = record
      size: SizeUInt;
      length: SizeUInt;
      contents: PAnsiChar;
    end;
    
    ...
    
    procedure AllocMyString(var S: TMyString; L: SizeUInt);
    begin
      S.size := 0;
      S.length := L;
      GetMem(Pointer(S.contents), L);
    end;
    
    procedure ReallocMyString(var S: TMyString; L: SizeUInt);
    begin
      S.size := 0;
      S.length := L;
      ReAllocMem(Pointer(S.contents), L);
    end;