0

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;
}
  • This sounds like a confusing idea. Why not write two functions - one for struct1, the other for struct2 - and use `select` to choose them? `if(select) { myFun((void *)&t1,select);` - you already know that `select` is true here. – KamilCuk Jul 02 '22 at 07:49
  • 1
    The technique you're looking for is called _opaque pointers_. You'll need a kind of common tag additionally (e.g. an enum), to decide what's actually passed. – πάντα ῥεῖ Jul 02 '22 at 07:50
  • `arg` isn't dereference-enabled as `void*`. If you're going to pursue this madness instead of using multiple functions (which you should consider), it must be converted. Ex: `if (select) { struct1 *p = arg; p->a = 10; }` – WhozCraig Jul 02 '22 at 07:50
  • thank you for your response. this is the sample code only my actual code want to pass different structure ina single function with one argument – Dhaneesh lal.D.R Jul 02 '22 at 08:09
  • Use the solution @selbie suggested. Also make sure to fix your scanf otherwise you get segmentation fault. `scanf("%d",&select);` – kostakis Jul 02 '22 at 08:17

1 Answers1

2

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;
    }
}
selbie
  • 100,020
  • 15
  • 103
  • 173