Passing two different structs into same function

后端 未结 4 942
萌比男神i
萌比男神i 2021-01-06 01:34

I have 2 different sized structs and I would like to have one function in which I can pass them into. However, I do not know how to define the parameter of the function to

4条回答
  •  悲&欢浪女
    2021-01-06 02:22

    It's not really possible. You could create a union that holds the two structs plus some kind of identifier. You then pass the union in and use the identifier to work out which struct is contained in it.

    typedef struct sp1 {
        int a;             // 2 byte
        int b;             // 2 byte
        int c;             // 2 byte
        int d;             // 2 byte
    }  person1_t;          // 8 bytes
    
    
    typedef struct sp2 {
        int a;            // 2 byte
        DeviceAddress b;  // 8 bytes
        int c             // 2 bytes
        float d;          // 4 bytes
    }  person2_t;         // 16 bytes
    
    typedef union {
        person1_t person1;
        person2_t person2;
    } people;
    
    function print_struct(people *p, int id) // e.g. id == 1, struct is person1
    {
        switch (id)
        {
             case 1: // Do person 1 things
             break;
    
             case 2: // Do person 2 things
             break;
    
             default: // Error
             break;
        }
    }
    

提交回复
热议问题