Hab ich wohl etwas zu schnell gelesen ;-)
Du willst die Werte kriegen nicht setzen, aha.
C hat eine "call by value" Semantik und da es die Referenzen aus C++ nicht kennt muss Du wohl mit Pointern arbeiten um "call by reference" zu kriegen.
Will ja jetzt nicht boese klingen, aber wenn Dir das entgangen sein sollte, dann besorg Dir erstmal ein Buch zu C/C++ ;-)
Code:
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
enum {
NAME = 5,
NIX
};
void func( int code, ... ) {
char *_name;
char *foo = "schlumpf";
int end;
va_list ap;
va_start( ap, code );
for( end = 0; !end ; code = va_arg( ap, int ) ) {
switch( code ) {
case NAME:
_name = ( char * )malloc( strlen( foo ) + 1 );
/* DONT USE THIS: strncpy( _name, foo, strlen( foo ) + 1 ); */
/* false security:
strncpy( ..., foo, strlen( foo) +1 )
is nothing else than
strcpy( ..., foo);
*/
strcpy( _name, foo);
/* va_arg must be used here, too */
*(va_arg(ap, char**)) = _name;
break;
case NIX:
/* va_arg must be used here, too */
*(va_arg(ap, int*)) = 42;
break;
case NULL:
end = 1;
break;
default:
/* FIXME error handling */
}
}
va_end( ap );
}
int main(){
char *name;
int nix;
/* call with address of variable instead of value.
If we dereference this address as a pointer inside of func()
we will be able to change the value
*/
func( NAME, &name,
NIX , &nix,
NULL );
printf("%s - %u\n", name, nix );
/* don´t forget to free allocated memory */
free(name);
}
[ 19. Mai 2001: Beitrag editiert von: jgbauman ]
Lesezeichen