Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2010-01

Pointer to an array of PChar strings

3 messages · 2 people · –

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Graeme Geldenhuys

Hi,

I'm working with a C library that returns an array of strings. So that is type PPChar. I C library does the array allocation, but doesn't do the freeing of the array.

How am I supposed to free an array of PChar strings? I think I need to improve my iteration too, because I'm moving the pointer of wlst, so I probably need to make a backup of the original pointer before the iteration.

My code looks as follows:

---------------------------------
 var
    s: PChar;
    wlst: PPChar;
    i: integer;
    n: integer;
  begin
      // Returns an array of PChar strings. i = number of elements in array
      i := Hunspell_suggest(SpellPtr, wlst, s);
      if i > 0 then
        writeln(Format('  %d suggestions:', [i]));
      for n := 1 to i do
      begin
        writeln('     ', UTF8Decode(wlst^));
        Inc(wlst, SizeOf(Pointer));
      end;
    end;
---------------------------------

Regards,
- Graeme -

fpGUI Toolkit - a cross-platform GUI toolkit using Free Pascal http://opensoft.homeip.net/fpgui/
Marco van de Voort
to Graeme Geldenhuys

In our previous episode, Graeme Geldenhuys said:

Show quoted text 8 lines
I'm working with a C library that returns an array of strings. So that is type PPChar. I C library does the array allocation, but doesn't do the freeing of the array. How am I supposed to free an array of PChar strings? I think I need to improve my iteration too, because I'm moving the pointer of wlst, so I probably need to make a backup of the original pointer before the iteration.

The array is 0 terminated, iow the last array of pchar is nil.

var p2 : ppchar;
If assigned(p) then
  begin
    p2:=p;
    while assigned(p2) do
      begin
        cfree(p2);
        inc(p2);
      end;
    cfree(p);
  end;

where cfree is the free() corresponding to the malloc with which it was allocated in the lib. (usually libc's)

Graeme Geldenhuys
to Marco van de Voort

2010/1/19 Marco van de Voort :

where cfree is the free() corresponding to the malloc with which it was allocated in the lib. (usually libc's)

Thanks for the repy. In the end I found the library I was using was old. The newer library has a function that does the free'ing of that list for me.

Regards, - Graeme - _______________________________________________ fpGUI - a cross-platform Free Pascal GUI toolkit http://opensoft.homeip.net/fpgui/