Hi. If I don't use varargs and use a pointer to an array I'd have to dynamically allocate an array everytime I wanted to create a string using other strings (for example a list of errors) and variables.
I read this is a big problem for OS4 compatibility, is there a way around this still using varargs?
What about MOS, doesn it have the same problem ?
The bellow code is some example I made last night. Using Piru's suggestion the code size more than halved (was almost 200 lines).
However the bloody thing doesn't work. I couldn't find the bug, so since the code size is small and it's probably a stack related problem that I wouldn't find anyway I decided to post it here in hope some benevolent soul finds it :roll:
#include <exec/memory.h>
#include <exec/types.h>
#include <stdio.h>
BOOL AllocAndCpyStr (char *CtrlStr, char **dest, ...);
void CountChrs (char ch, LONG *StringSize);
void CpyChr (char ch, char *dest);
int main (int argc, char **argv)
{
char *a = "Error a";
char *b = "Error b";
char *c = 0;
/* .. Other function code...*/
/* Make information strings without having to allocate an array everytime for each */
/* Suppose both error a and b happened. Allocate string with info without having make */
/* an array with pointers a and b plus other data we want to put into final string */
/* Also serves to test AllocAndCpyStr */
if (AllocAndCpyStr ("%s %c %s \n Test number is %d", &c, a, ' ', b, 44))
printf ("Sucess, concatenation and allocation result is:\n %s\n",c);
else
printf ("Failed\n");
if (c)
FreeMem (c, strlen (c) + 1);
exit (0);
}
/* printf() like, except it copies resulting string to it's own allocated chunk, whose ptr is put in *dest */
/* uses StrToRawDF */
BOOL AllocAndCpyStr (char *CtrlStr, char **dest, ...)
{
LONG StringSize = 0;
BOOL Result = FALSE;
/* Check total size */
RawDoFmt (CtrlStr, &dest + 1, (void (*)())CountChrs, &StringSize);
/* Allocate space 4 strings */
if (!(*dest = (char *)AllocMem (StringSize, MEMF_ANY | MEMF_CLEAR)))
{ printf ("Out of memory in report!\n");
goto END;
}
printf ("Allocated space (resulting string size) was %ld bytes\n\n", StringSize);
Result = TRUE;
/* Copy over strings */
RawDoFmt (CtrlStr, &dest + 1, (void (*)())CpyChr, *dest);
END:
return (Result);
}
/* Count nr. of times it's called (= string size) */
void CountChrs (char ch, LONG *StringSize)
{ ++*StringSize;
}
void CpyChr (char ch, char *dest)
{ *dest++ = ch;
}