Cannot construct dynamic array in dev-pascal

438 Views Asked by At

I am still a beginner, so please forgive me if it is a stupid mistake or something. I want to write a program to generate prime numbers from 2 to n, and n is user-defined. Since I do not know n at the start of the program, I want to construct a dynamic array and setlength(n) afterwards. Here is a snippet of my code:

    program D401;
    type
       arr = array of int64;
    var
       x : int64;
       a : arr;
    begin
        readln(x);
        setlength(a, x);
    end.

But it won't work and and it says: Fatal: Syntax error, [ expected but OF found

I also tried this:

    program D401;
    var
       x : int64;
       a : array of int64;
    begin
        readln(x);
        setlength(a, x);
    end.

But it also produces the same error. I also used freepascal and GNU pascal but it also doesn't work. Is it dev-pascal's problem or it is not updated or something?

Thanks in advance.

2

There are 2 best solutions below

3
On

Dev Pascal is ancient and uses old compilers that do not support dynamic array syntax. Simply put you should not use it today.

If you want a free development environment using an up-to-date Pascal compiler the best option is Lazarus, using a modern version of freepascal.

0
On

It doesn't matter in the modern world. But I am writing my answer for those who want to deliberately use the outdated GNU Pascal. I know a little about GNU Pascal but suggest a pointer based approach:

program dynarr;

type
  TElem = integer;
  TPArray = ^TElem;

var
  pArray: TPArray;
  length, i: INTEGER;

begin
  length := 10;
  GetMem(pArray, length * sizeof(TElem));

  for i := 0 to length-1 do
    (pArray+i)^:=i;
  for i := 0 to length-1 do
    writeln((pArray+i)^);

  FreeMem (pArray, length * sizeof(TElem));
  readln;
end.

Compile with --pointer-arithmetic option