Passing two different structs into same function

后端 未结 4 941
萌比男神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:14

    typedef struct p1 {
        int a;             // 2 byte
        int b;             // 2 byte
        int c;             // 2 byte
        int d;             // 2 byte
    } person1;                // 8 bytes
    
    
    typedef struct p2{
        int a;            // 2 byte
        DeviceAddress b;  // 8 bytes
        int c             // 2 bytes
        float d;      // 4 bytes
    } person2;               // 16 bytes
    
    typedef enum ptypes {
        PERSON1,
        PERSON2
    } person_type;
    
    typedef union p1_or_p2 {
        person1 p1;
        person2 p2;
    } person1_or_person2;
    
    typedef struct p {
        person1_or_person2 person;
        person_type type;
    } person;
    
    // Creating a person struct variable:
    person p;
    person1 p1;
    p1.a = 5;
    p1.b = 2;
    p.type = PERSON1;
    p.person = (person1_or_person2) p1;
    
    void print_struct(person p) {
         switch (p.type) {
            case PERSON1:
                // actions for person1 here....
                  // you can access person1 like this:
                     p.person.p1;
            break;
            case PERSON2:
                // actions for person2 here....
                  // you can access person2 like this:
                     p.person.p2;
            break;
         }
    }
    

提交回复
热议问题