How to pass different structure in a single function as argument

64 Views Asked by At

I have 2 structure name struct1, struct2. also i have one manipulation function named "myFun"

void myFun(/one pointer argument/)

i have a set flag , if set flag is 1 i need to pass struct1 pointer as myFun argument if set flag is 0 i need to pass myFun argument as struct2 pointer .

is it possible, how can i do this

sample (non working) code i tried is shown below.

#include <stdio.h>
#include <string.h>

typedef struct struct1{
    int a;
    int b;
}struct1;

typedef struct struct2{
    int a;
}struct2;
void myFun(void *arg, int select)
{
    if(select)
    {
        arg->a = 10;
        arg->b = 20;
    }
    else
    {
        arg->a = 100;
    }
}
int main() {
    // Write C code here
    int select = 0;
    struct1 t1;
    struct2 t2;
    printf(enter the select option 0 or 1);
    scanf("%d",select);
    if(select)
    {
        myFun((void *)&t1,select);
    }
    else
    {
         myFun((void *)&t2,select);
    }
    return 0;
}
1

There are 1 best solutions below

0
selbie On

Use a cast:

    if(select)
    {
        struct1* ptr = (struct1*)(arg);
        ptr->a = 10;
        ptr->b = 20;
    }
    else
    {
        struct2* ptr = (struct2*)(arg);
        ptr->a = 100;
    }
}

Actually the explicit cast from void* isn't necessary in C as it would be in C++. So this suffices as well:

    if(select)
    {
        struct1* ptr = arg;
        ptr->a = 10;
        ptr->b = 20;
    }
    else
    {
        struct2* ptr = arg;
        ptr->a = 100;
    }
}