Lars Tackmann <roland@diku.dk> writes:[color=blue]
> Hi - I need a function to concatenate a variable number of strings.
> I have two ideas but cannot deside which way to go.
>
> 1) use the "stdarg" macros - if i use these macros it will be easy
> to step through the strings, but as I see it (and I may be wrong here)I
> need to pass the number of strings to the function - which is difficult in
> this context.
>
> 2) using a pointer array as argument to the function. Here the length is
> again a problem - the pointer array is passed on the stack so I cannot
> use pointer arithmetic to calculate the length of the array. although
> the final string will be created via malloc - i need a way to decide how
> much memory to allocate on the heap.[/color]
Pete pointed out that you can use a NULL pointer to terminate an
array; you can do the same with a stdarg argument list. A call might
look like this:
my_func("foo", "bar", "baz", (char*)NULL);
(Yes, the cast is necessary.)
Inside my_func(), you can traverse the argument list once to add up
the sizes, malloc() the needed memory, then traverse the list again to
copy the strings to the malloc()ed space.
On the other hand, why is passing the number of strings difficult? It
could be a maintenance headache, as you need to change the number if
you add or remove arguments, but the number is constant and you can
determine it at the call.
If you need to pass a number of arguments that's determined at
execution time, you probably need to build an array of pointers and
pass it.
--
Keith Thompson (The_Other_Keith)
kst-u@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)