Search code examples
cc89

Passing argument by void** to function


I'm trying to pass arguments by a function using a void * to give any type of arguments. But for some reasons I don't understand, no data can be read inside of the function.

This is a reproduced behaviour of a company function. Live on Coliru

#include <stdio.h>

typedef struct
{
    double d1, d2;
} S;

double doStuff(void ** args)
{
    double * a = (double*)args;

    printf("a[0] = %lf\n", a[0]);
    printf("a[1] = %lf\n", a[1]);

    double r = a[0] + a[1];
    return r;
}

int main(void) {

    S s;
    s.d1 = 10.0;
    s.d2 = 10.0;

    S* ptr = &s;

    void* args[2];
    args[0] = &ptr->d1;
    args[1] = &ptr->d2;

    double d = doStuff(args);

    printf("d = %lf\n", d);

    return 0;
}

And it's output

a[0] = 0.000000
a[1] = 0.000000
d = 0.000000

Solution

  • You should change your code to:

    double doStuff(void ** args)
    {
        double ** a = (double**)args;
    
        printf("a[0] = %lf\n", *a[0]);
        printf("a[1] = %lf\n", *a[1]);
    
        double r = *a[0] + *a[1];
        return r;
    }
    

    EDIT

    The OP asked for a change in main instead of doStuff (which s/he does not own).

    Now, as noted by @Eugene Sh, the function doStuff is crippled because it asks for a double pointer argument, but uses as a pointer to double.

    The change in main is just pass around a pointer to double, but cast to void** just to make the compiler happy:

    int main(void) {
    
        S s;
        s.d1 = 10.0;
        s.d2 = 10.0;
    
        S* ptr = &s;
    
        double args[2];     // our pointer to double
        args[0] = ptr->d1;
        args[1] = ptr->d2;
    
        double d = doStuff((void**)args); // cast to void**
    
        printf("d = %lf\n", d);
    
        return 0;
    }