Lazarus
Free Pascal => General => Topic started by: airpas on May 21, 2014, 03:39:41 pm
-
hi
look at this example , the procedure changestr works only if the argument is ppchar , and not for pchar
uses strings;
type
ppchar = ^pchar;
procedure changestr(s : ppchar);
begin
getMem(s^,16);
strcopy(s^,'Hello World');
end;
var
p : pchar;
begin
changestr(@p);
writeln(p);
readln;
end.
why it doesn't work when using only one pointer to char e.g
uses strings;
type
ppchar = ^pchar;
procedure changestr(s : pchar);
begin
getMem(s,16);
strcopy(s,'Hello World');
end;
var
p : pchar;
begin
changestr(p);
writeln(p); // print nothing !!
readln;
end.
-
In the first example you 'force' a parameter by reference call.
In the second a parameter by value hence there is no returning value stored in p.
You probably create a memory leak though.
-
This returns a value and avoids the memory leak
program project1;
uses strings;
procedure changestr(var s : pchar);
begin
GetMem(s,16);
strcopy(s,'Hello World');
end;
var
p : PChar;
begin
changestr(p);
WriteLn('"',p,'"');
Freemem(p, 16);
ReadLn;
end.