[fpc-pascal] Array clearing

Jürgen Hestermann juergen.hestermann at gmx.de
Tue Apr 4 15:18:43 CEST 2017


Am 2017-04-04 um 13:55 schrieb Ryan Joseph:
 > Doesn’t iterating the array default the purpose of FillChar?
 > The goal was the most efficient way clear the array with zero’s.
 > Even if the array if nested 3 levels deep (anArray[x][y][z])
 > it should (I hope) be a contiguous block of memory that was allocated (correct me if I wrong please).

No. If you have a dynamic array of multiple levels it
does not generate a continuous block for all levels.
Only the last level (if it is an array of integer or other non-managed type) is just that.
A (dynamic) array of array if an array of pointers.
Only for static arrays all levels are a continuous block.

The first level of a multiple level (dynamic) array is an array of pointers (array of array).
So you have a continuous block of pointers on the first level.

Each (!) second level array also is an array of pointers (array of array).

Only the last level is an array of integer (or whatever).

Therefore, for a 3x3x3 array you have 3 pointers on the first level.
Each of these pointers (MyArray[x]) again points to an array of 3 pointers.
And on the last level (MyArray[x,y]) each pointer points to an array of integer.
So you have 3x3=9 continuous blocks of 3 integers which can be located anywhere in memory.

BTW:
Each level of nested dynamic arrays can have individuell size.
On a 2-dimensional array

var MyArray : array of array of integer;

you can do:

SetLength(MyArray,3);
SetLength(MyArray[0],2);
SetLength(MyArray[1],3);
SetLength(MyArray[2],4);

So MyArray[0] points to an array of 2 integers,
MyArray[1] points to an array of 3 integers and
MyArray[2] points to an array of 4 integers.




More information about the fpc-pascal mailing list