Hello I'm new to pointers and am not sure what I'm doing. What's wrong at this code:
procedure TMain.DoRun;
var
...
ArtistPtr : ^String;
DurationPtr : ^String;
BpmPtr : ^String;
KeyPtr : ^String;
PriorityPtr : ^String;
begin
Str:='';
ArtistPtr :=Nil;
ArtistPtr:=@Str;
DurationPtr :=Nil;
DurationPtr:=@Str;
BpmPtr :=Nil;
BpmPtr:=@Str;
KeyPtr :=Nil;
KeyPtr:=@Str;
PriorityPtr :=Nil;
PriorityPtr:=@Str;
...
ArtistPtr^:=GetTagFromFile(P, 'TAG:artist');
ArtistPtr^:=ArtistPtr^.Substring(0, ArtistPtr^.Length);
end;
How can I correctly use pointers?
Personally, I wouldn't dare to use pointers for anything managed, the Strings are just that kind of type. You can't be sure what will happen using them in different scopes, e.g. after returning from the procedure, passing the pointer to another one, etc.
Actually
^String is of "pointer to pointer" type, because internally String is a pointer.
One can intermix Strings with PChars but only when he have a deep understanding what he's doing. Usually it was made for performance reasons.
Specifically for your case - the following statement:
Makes the
Str a Nil pointer, i.e. pointing to nowhere. The FPC compiler is aware of that and and comparing it to '' (empty string) is OK, but there is actually _no memory allocation_ for it. Then:
ArtistPtr :=Nil;
ArtistPtr:=@Str;
From now on, you can easily confuse the compiler how to deal with the
ArtistPtr^, especially if you do something to obscure the pointed type. At least you have a variable with a different life-cycle than the one it points to (non-managed vs managed). See
dangling pointers.
Why you're doing that (taking pointers to strings) in the first place?
As
egsuh wrote, it should be something with the
GetTagFromFile. What is the implementation of it?