Passing two different structs into same function

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

    Unfortunately, the only choice for unrelated structures in C is to pass pointers to the structures untyped (i.e. as void*), and pass the type "on the side", like this:

    struct person1_t {
        int a;             // 2 byte
        int b;             // 2 byte
        int c;             // 2 byte
        int d;             // 2 byte
    }  person1;
    
    struct person2_t {
        int a;            // 2 byte
        DeviceAddress b;  // 8 bytes
        int c             // 2 bytes
        float d;      // 4 bytes
    }  person2;
    
    void print_struct(void* ptr, int structKind) {
        switch (structKind) {
            case 1:
                struct person1 *p1 = (struct person1_t*)ptr;
                // Print p1->a, p1->b, and so on
                break;
            case 2:
                struct person2 *p2 = (struct person2_t*)ptr;
                // Print p2->a, p2->b, and so on
                break;
        }
    }
    
    print_struct(&person1, 1);
    print_struct(&person2, 2);
    

    This approach is highly error-prone, though, because the compiler cannot do type checking for you.

提交回复
热议问题