Re: Passing pointer to c array

new topic     » goto parent     » topic index » view thread      » older message » newer message

Irv Mullins wrote:

> I need to create a null-terminated array of strings in
> Euphoria, and obtain a pointer to the array.


WARNING: Untested Code Ahead! Note that the poke4() pokes all the addresses
at once - pretty spiff! A similar trick could be done to gather the
addresses if you knew how many there were (you could poke the count into the
head, and advance the address past it, like a Pascal string), but it's
probably not worth the effort.

To allocate the string array, you could do this:

   function allocateStringArray( sequence s )

      atom address

      -- allocate space for the array pointers, plus a null
      address = allot( length( s ) + 1 ) * 4

      -- for each string in the sequence...
      for i = 1 to length( s ) do

         -- ... replace it with a pointer to itself
         s[i] = allocate_string( s[i] )

      end for

      -- place an end of array marker
      s = append( s, 0 )

      -- poke the addresses into the array.
      poke4( address, s )

      return address

   end function


Of course, you need to destroy the array after you've passed it to the
function, or you'll just be gobbling up memory.

   procedure freeStringArray( atom address )

      atom ptr, strPtr

      -- point to the beginning of the array
      ptr = address

      -- process until end of array
      while 1 do

         -- get the pointer from the array
         strPtr = peek4u( ptr )

         -- end of array?
         if strPtr = 0 then
            exit
         end if

         -- free the pointer
         free( strPtr )

         -- move to the next array element
         ptr += 4

      end while

      -- free the array
      free( address )

   end procedure


Hope this helps!

-- David Cuny

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu