Hello Folks!
I'm having a C programming question: I want to write a function with variable argument lists, where the specific types of each argument is not know - only its size in bytes. That means, if I want to get an int-Parameter, I (somewhere before) define: There will be a parameter with sizeof( int ), that is handled with a callback-function xyz.
My variable argument function should now collect all information from its call, the real data-type specific operations (which also can be user-defined data types) are processed only via callback-functions.
At the standard va_arg-functions, it is not possible to say "get me a value of X bytes from my parameter-list", so I thought to do it this way. My data-type is double in this case, but it can be any other number of bytes (and even variable ones).
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
int fn( int anz, ... )
{
char* p;
int i;
int j;
va_list args;
char* val;
char* valp;
int size = sizeof( double );
va_start( args, anz );
val = malloc( size );
for( i = 0; i < anz; i++ )
{
memcpy( val, args, size );
args += size;
printf( "%lf\n", *( (double*)val ) );
}
va_end( args );
}
int main()
{
fn( 1, (double)234.2 );
fn( 3, (double)1234.567, (double)8910.111213, (double)1415.161718 );
return 0;
}
It works for me, under Linux (gcc). But my question is now: Is this really portable? Or will it fail under other systems and compilers?
My alternative approach was to replace
memcpy( val, args, size );
args += size;
with
for( j = 0; j < size; j++ )
val[j] = va_arg( args, char );
but then, my values went wrong.
Any ideas or help on this?