Nicola Girardi a écrit :
Hi fine GPC hackers, please take a look at this foolish code, I, as a novice, have a little problem with pointers in Pascal ;-) (I wonder why I don't just keep using C:))
: type : PStrList = ^TStrList; : TStrList = record : Next : PStrList; : S : TString; : end; : : var : StringList : PStrList; : : procedure Foobar; : var : Str : PStrList = StringList; : begin : repeat : New(Str); : Readln(F (* : Text *), Str^.S); : if Length(Hdr^.S) = 0 then : break; : Str := Str^.Next;
Here Str^.next contains only garbage and you put this garbage into Str...
: until False; : end;
Due to the assignment of StringList to Str, at the end of Foobar I'd get StringList not to be the head of the list but the last element. How can I keep a pointer which always points to the first element? Maybe that's really easily done, but of course in Pascal it doesn't seem that it works like in C, and I'm out of manuals ;-)
Look to iteratordemo.pas in the demo programs which come with gpc, especially the procedure ReadList which does exactly what you want. You need an extra level of indirection.
Maurice
On Wed, Oct 11, 2000 at 08:54:57PM +0200, Maurice Lombardi wrote: [...] | Look to iteratordemo.pas in the demo programs which come with gpc, especially the procedure ReadList | which does exactly what you want. You need an extra level of indirection.
Thanks a lot!
*cheers*
Nicola Girardi wrote:
On Wed, Oct 11, 2000 at 08:54:57PM +0200, Maurice Lombardi wrote: [...] | Look to iteratordemo.pas in the demo programs which come with gpc, especially the procedure ReadList | which does exactly what you want. You need an extra level of indirection.
I should note that that's *one* way to do it. Not everyone likes double pointers. There are ways to do it with simple pointers, but they require some `if' branches. I prefer double pointers (and incidentally this demo program was written by me), and I think after using them a few times, you get used to them, and the resulting code is more compact...
Maybe that's really easily done, but of course in Pascal it doesn't seem that it works like in C, and I'm out of manuals ;-)
BTW, it's exactly the same in C (apart from syntax, of course). There are cases where you need pointers in C, but not in Pascal (reference parameters), but in cases like this one, you need pointers in both languages, and the use is the same (i.e., also in C you can use double pointers or simple pointers and `if', but the original code, translated directly into C, also wouldn't work)...
Frank