Hi. THis is the 1st time I mess with this. I wanted to create a function that receives a ptr and a variable number of strings and then allocates enouph memry to the concatenation of all strings passing the address to the received ptr, and finally concatenates all strings in the order they are passed. To prove myself bellow is my first working piece (of art :lol: ) of code that does this.
Anyway, what I want to know is if there is a way to have va_arg() start passing arguments after the 2nd argument (eg start in the 3rd), or is this impossible ? The way I get the 3rd arguement the 2nd time (having to use va_arg() one time to pass by the 2nd first) seems a bit hackish...
#include <exec/memory.h>
#include <exec/types.h>
#include <stdio.h>
#include <stdarg.h>
WORD StringSize = 0;
BOOL AllocAndCpyStr (int num, char **dest, ...);
int main (int argc, char **argv)
{
char *a = "String a test, ";
char *b = "string b test";
char *c;
if (AllocAndCpyStr (3, &c, a, b))
printf ("Sucess, concatenation and allocation result is:%s\n",c);
else
printf ("Failed");
if (*c)
FreeMem (c, StringSize);
exit (0);
}
/* DON'T FORGET 2 INCLUDE STDARG.H */
/* Allocates space 4 and copies all strings to dest, in order of arguments */
BOOL AllocAndCpyStr (int num, char **dest, ...)
{
va_list argptr;
BOOL Result = FALSE;
char *String;
char **Destination;
int count;
/* Initialize argptr */
va_start (argptr, num);
Destination = va_arg (argptr, char **);
/* Allocate space 4 strings */
for (count = num - 1; count; count--)
{ String = va_arg (argptr, char *);
printf ("string: %s\n", String);
StringSize += strlen (String);
}
StringSize++; /* 4 the last NULL */
printf ("Allocated space is %d bytes\n\n", StringSize);
if (!(*Destination = (char *)AllocMem (StringSize, MEMF_ANY | MEMF_CLEAR)))
printf ("Out of memory in report!\n");
/* Copy over strings */
else
{ va_end (argptr);
va_start (argptr, num);
va_arg (argptr, char **);
for (num -= 1; num; num--)
{ strcat (*Destination, va_arg (argptr, char *));
}
Result = TRUE;
}
/* do orderly shutdown */
va_end (argptr);
return (Result);
}