1
votes

I've read i can't really 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? If so, how would one go about it? I don't want to use a built-in pascal dynamic array because it kind of defeats the purpose of making my own string type.

From comments, it seems like ISO pascal (both standard and extended) doesn't support such things. How do i do it in free pascal then?

1
Yes, this can be done, and it can be done in many different ways. It also depends a bit on what kind of Pascal you are using. There are several different versions of Pascal used today. (FreePascal and Delphi are two of them.) Also, depending on the type of Pascal you are using, a dyn array approach might not defeat the purpose that much. Finally, I don't know what you mean when you say that you cannot "really dynamically allocate an array in Pascal". - Andreas Rejbrand
@AndreasRejbrand i thought about ISO pascal. What i meant by that was that since arrays are each it's own type and so dynamically creating types wouldn't work. - Soft Waffle
The Standard Pascal (ISO 7185) does not have malloc, GetMem or other variable-length allocation functions, so it seems that the variable-length contents cannot be allocated in a conforming program. The Extended Pascal (ISO 10206) does not have them either. - Doj
@Doj so extended pascal is a standard pascal? alright, noted. So, pascal is really limited then? sad. seems like such a good language - Soft Waffle
There is widely used term "Standard Pascal" which refers only to the ISO 7185. The term "Extended Pascal" refers only to the ISO 10206. Both ISO standards are considered outdated and mainly used in educational purposes. Free Pascal and Delphi have their own pascal dialects. - Doj

1 Answers

2
votes

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;