[fpc-pascal] Questions regarding arrays

Michael Van Canneyt michael at freepascal.org
Thu Sep 23 09:46:13 CEST 2010

On Thu, 23 Sep 2010, Graeme Geldenhuys wrote:

> Hi Michael,
> On 23 September 2010 00:49, Michael Müller wrote:
>> So when the array memory is allocated by the calling function and freed
>> by another function and you only what to be able to access the elements
>> using the array braces you should use the static array approach. But I
>> would define the static array type as follows
>> TAtomArray = array[0..MaxInt] of TAtom; // or whatever is the allowed maximum index
>> to avoid that Pascal will raise a range checking error when you activate range checking.
> Ha, I think a light bulb just came on! :-)
> So let me see if I got this right. I defined TAtomArray as a static
> array with a single element. In static arrays, all elements follow
> each other in sequence in memory. I only know the length of the static
> array after the C API call, but because I know the memory address of
> the first element in the array, I can access the other elements too.
> And because I currently have range-checking disabled, Pascal doesn't
> complain that I am going over the bounds of my TAtomArray definition.
> If I got that right, I should then also know how to pass such an array
> to the C API (which was going to be my next question). The easiest
> would be to create a static array with a largish size in Pascal (for
> DND mime types, 30-50 elements should be plenty), then pass the
> address of element 0 to the C API, and another parameter that
> specifies the length of the array (only elements with actual data).
> Once again, thank you very much for taking the time to explain things
> in such detail. I really helps a lot. As for the differences between
> static and dynamic arrays, and a string array - i think I'll annotate
> my FPC Language Reference docs with what you mentioned, or see if
> Michael van Canneyt could add that info into the official docs so
> others can benefit too.

What do you want added ? I haven't seen anything which isn't already
mentioned somehow in the docs ?

> Out of interest. Do you know if dynamic array elements are in sequence
> (storage area in memory) too - like static arrays? So could I do the
> same as above, but instead of using a static array, use a dynamic
> array, and pass the address of the first element to the C API?


> As for freeing the array that the C API returned to me... I don't do
> the freeing, I simply notify the C library when I am done using the
> array, and the library does the freeing for me.

No. This you cannot do, since the pascal memory manager allocated the 
array, it must also free it. The C memory manager has no idea about this
'memory'. You must manually do a SetLength(myarray,0);


More information about the fpc-pascal mailing list