Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two struct one function

Tags:

c

avr

I would like to do in C code something like that to call one function with can operate on two similar but not the same struct. Now I have two function that do the same but different type data. I can't change struct to the same data type. The struct must have different data type. I tried by void pointer but doesn't work. Dynamic cast pointer but I don't think it's possible in C code. I can't use allocate memory dynamically malloc etc. It is possible to implement?

    typedef struct st1_tag
    {
        uint32_t a;
        uint16_t b;
        uint16_t tab[10];
    }st1_t;

    typedef struct st2_tag
    {
        uint8_t a;
        uint16_t b;
        uint32_t tab[10];
    }st2_t;

...
    
    st1_t x1;
    st2_t x2;

...

void foo_1(void)
{
    if(x1.b > 2)
    {
        //to do someting on data struct x1
    }
}

void foo_2(void)
{
    if(x2.b > 2)
    {
        //to do something similar like in foo1 but data type field of struct are not the same.
    }
}

void foo3(void)
{
    foo1();
    foo2();
}
like image 799
szkarbun Avatar asked May 06 '26 18:05

szkarbun


1 Answers

"I tried by void pointer but doesn't work.".

And:

"I can't use allocate memory dynamically malloc"

I am not sure in what way using void * did not work, but the following defines one function, that can be used to convey either type of struct via void *, without using dynamic allocation:

  typedef struct st1_tag
    {
        uint32_t a;
        uint16_t b;
        uint16_t tab[10];
    }st1_t;
    st1_t s1, *pS1;   

    typedef struct st2_tag
    {
        uint8_t a;
        uint16_t b;
        uint32_t tab[10];
    }st2_t;
    st2_t s2, *pS2;
    
    typedef enum {
        TYPE_1,
        TYPE_2,
        TYPE_MAX
    }type_e;


void operate_on_two_different_struct(void *s, type_e type);   
    
int main()
{
    st1_t st1 = {18, 25, {1,2,3,4,5,6,7,8,9,10}};
    st2_t st2 = {10, 25000, {10,20,30,40,50,60,70,80,90,100}};    
    
    operate_on_two_different_struct(&st1, TYPE_1);
    operate_on_two_different_struct(&st2, TYPE_2);
    
    return 0;
}

void operate_on_two_different_struct(void *s, type_e type)
{
    switch(type) {//demonstrates conveyance of data, nothing else.
        case TYPE_1:                
            pS1= (st1_t *)s;
            break;
        case TYPE_2:
            pS2 = (st2_t *)s;
            break;
    }
}
        

If you need more specificity than this, or some other information, post a comment under.

like image 123
ryyker Avatar answered May 09 '26 12:05

ryyker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!