Recent

Author Topic: pointer to pointer  (Read 2249 times)

airpas

  • Full Member
  • ***
  • Posts: 179
pointer to pointer
« 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.

eny

  • Hero Member
  • *****
  • Posts: 1586
Re: pointer to pointer
« Reply #1 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.
All posts based on: Win10 (Win64); Lazarus 1.8.0 'stable' (#56594 win64) unless specified otherwise...

howardpc

  • Hero Member
  • *****
  • Posts: 3043
Re: pointer to pointer
« Reply #2 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.