Page 1 of 1

How to define the size of an array during runtime?

Posted: Mon Jun 19, 2023 6:07 pm
by Zinn
I would like to create an ARRAY and define its size during runtime instead of compilation time. Why? This year I have done a Java course. After that course I translated class ArrayList from the library java.util.ArrayList to Component Pascal. This library automatically extend its size of the array automatically if it is to small. It is done by creating a new ARRAY of bigger size and copy the old ARRAY to the new one. The old array is deleted after the expansion.

Re: How to define the size of an array during runtime?

Posted: Sat Jun 24, 2023 4:51 am
by cfbsoftware
For many years the Gardens Point implementation of Component Pascal has had a language extension for extensible array types. These are called vectors:
Values of these vector types are dynamically allocated, and automatically extend their capacity when an append operation is performed on an array that is already full. Vectors may be declared to have any element type, and extend their length using amortized doubling. In most circumstances when a linked list would otherwise have been used the vector
types are faster, more memory efficient, and allow memory-safe indexing. Elements of vectors may be accessed using the familiar index syntax, with index values check
For more details read section 4.6 Extensible arrays: the vector types in the GPCP Release Notes.

The source code is available on the GitHub gpcp site.

Re: How to define the size of an array during runtime?

Posted: Sat Jun 24, 2023 7:49 am
by Josef Templ
you need to use a dynamic array, i.e. a POINTER TO ARRAY. Then you can specify the size with NEW.
In Java it is exactly the same but the syntax differs slightly😀

Josef

Re: How to define the size of an array during runtime?

Posted: Sun Jun 25, 2023 1:56 pm
by Zinn
Josef thank you very much for the hint. That is the solution of my problem.

Also thank you to Chris. I'll look on your solution later. I think Josef's way is more elegant.

- Helmut