Question

Is there a way to do something like this : ?

void set(void* data, void *value, t_flags type)  
{
    if (type & INT)
        *(int*)data = *(int*)value;
    if (type & UINT)
    (...)
}

int i;  
set(&i, 42, INT);

My set function works but I don't know how to call it with number, char '', or string "".

Edit : I've forgot the last argument, but the problem come from the 42 argument.

Was it helpful?

Solution

A few things. First, since you're using a void* (which is appropriate) for value, you need to pass a void* as your second argument, instead of a constant. This will work to copy one variable to the next, but there are more efficient ways.

Second, note that for passing a string, you need to pass a pointer to a char pointer, and the char* will get set by the function. (It's up to you whether it's a "soft copy" or "hard copy" - i.e. whether the pointer points to the same place in memory or to another copy of the same string. You said you had set implemented, so I'm guessing you already have it the way you want.

You haven't included your t_flags enum, so I guessed appropriate values.

char  c = 'c';
char* str = "str";
int   i = 42;
char  c2;
char* str2;
char  i2;

set(&c2, &c, CHAR); /* presumably you have a CHAR flag? */
set(&str2, &str, CHARPTR); /* presumably you have a CHARPTR flag? */
set(&i2, &i, INT);

The bigger question for me is why you would want to do this, especially since in your flag you already need to know the type. It's much cleaner (and has much better type checking) to simply do:

c2 = c;
str2 = str;
i2 = i;

I'm assuming this is just for learning about functions, or it's massively simplified for a complex issue. Either way, that's how you do it.

OTHER TIPS

Maybe you want this:

void set(void* data, void *value, t_flags type)  
{
    if (type & INT)
        *(int*)data = *(int*)value;
    if (type & UINT)
        *(unsigned int*)data = *(unsigned int*)value;
    if (type & STRING)
        strcpy((char*)data, (char*)value);
    ...
}

int i;  
char string[100] ;
set(&i, 42, 1<<INT);
set(string, "Hello world", 1<<STRING) ;

But it's weird anyway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top