Lazarus

Free Pascal => General => Topic started by: airpas on May 21, 2014, 03:39:41 pm

Title: pointer to pointer
Post 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
Code: [Select]

 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
Code: [Select]

 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.
Title: Re: pointer to pointer
Post by: eny on May 21, 2014, 03:51:52 pm
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.
Title: Re: pointer to pointer
Post by: howardpc on May 21, 2014, 04:10:38 pm
This returns a value and avoids the memory leak
Code: [Select]
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.