Grey Alien <gr**@andromeda.comwrote:
long AllocStruts(MyStruct s1, ...)
First of all, this signature implies that 1) space has already been
allocated for the arguments (not what you want), and 2) the structs
are being passed by value (not what you want).
{
long ret = -1 ;
/*allocate memory for all structs passed in*/
/* If an allocation fails, free all previously allocated memory and
return error */
return ret ; /* 0 == success, else eror
}
How may I implement such a func?.
I'm assuming that this isn't homework (apologies to the regulars if it
is); consider the following (hopefully correct) program:
/* Begin test.c */
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
struct foo {
char *bar;
};
int alloc_structs( int count, ... ) {
va_list vargs, freeargs;
int idx, jdx;
struct foo **ptr;
va_start( vargs, count );
va_copy( freeargs, vargs );
for( idx=0; idx < count; idx++ ) {
ptr=va_arg( vargs, struct foo ** );
*ptr=malloc( sizeof(struct foo) );
if( !*ptr ) {
for( jdx=0; jdx <= idx; jdx++ ) {
free( va_arg(freeargs,struct foo **) );
}
return 1; /* failure */
}
}
return 0; /* success */
}
int main(void) {
struct foo *baz;
struct foo *qux;
alloc_structs( 2, &baz, &qux );
baz->bar="foo";
qux->bar="bar";
printf( "%s %s\n", baz->bar, qux->bar );
return 0;
}
/* End test.c */
--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gmail.com | don't, I need to know. Flames welcome.