[fpc-pascal] about dynamic array

Michael Van Canneyt michael at freepascal.org
Fri May 7 11:34:51 CEST 2010



On Fri, 7 May 2010, spir ☣ wrote:

> On Fri, 7 May 2010 06:10:30 +0200
> cobines <cobines at gmail.com> wrote:
>
>> 2010/5/6 spir ☣ <denis.spir at gmail.com>:
>>> (By the way, started playing with TFPList already, and could not find how to get data back! I mean the symtric of add(). Even tried indexing (who knows, with the syntactic magic of modern language? ;-).)
>>
>> It is indexing.
>>
>> var
>>   l: TFPList;
>>   p: Pointer;
>>   index: Integer;
>> begin
>>   l := TFPList.Create;
>>   index := l.Add(p);
>>   p := l[index];
>> end;
>> [...]
>
> Thank you, I must have written a typo or messed up indices, since now it works fine. Still, remains a mystery about untyped pointers, illustrated by the code below:
>
> var
> 	l : TFPList;
> 	i : Integer;
> 	p : ^Integer;
> begin
> 	l := TFPList.Create;
> 	i := 1 ; new(p) ; p^ := i; l.Add(p);
> 	p := l[0] ; writeln(p^);
> 	writeln(l[0]^);			// error
> end.
>
> I cannot directly "fish" and use the pointer's target. Seems I always need to pass _via_ the pointer, then all is fine. It's not really annoying. But I don't understand the difference: in code, both versions are indeed strictly equivalent. I guess there's an implicit (pointer?) conversion somewhere?
> Are there cases where the pointer's mediation is not needed?

L[0] is an untyped pointer. Dereferencing it gives you a memory address,
but not a type. So the compiler doesn't know what to do with it.

p is a pointer to an integer. When dereferencing it, the compiler knows that
at the address an integer is waiting, and it knows how to deal with
integers.

Adding a typed pointer (p) to an untyped pointer list does not store 
the type information in the list, any type information available is 
lost: the compiler or the list do not remember that you stored a pointer
to an integer. They just remember the address, not the type.

Michael.


More information about the fpc-pascal mailing list