Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing two different structs into same function

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 accept 2 different structs.

My structs are below

struct {
    int a;             // 2 byte
    int b;             // 2 byte
    int c;             // 2 byte
    int d;             // 2 byte
}  person1;                // 8 bytes


struct {
    int a;            // 2 byte
    DeviceAddress b;  // 8 bytes
    int c             // 2 bytes
    float d;      // 4 bytes
}  person2;               // 16 bytes

function print_struct(struct& ?????)
{
     actions here....
}


print_struct(person1);
print_struct(person2);
like image 759
user1978109 Avatar asked Jan 14 '13 18:01

user1978109


2 Answers

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.

like image 76
Sergey Kalinichenko Avatar answered Sep 28 '22 03:09

Sergey Kalinichenko


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;
    }
}
like image 36
Joe Avatar answered Sep 28 '22 03:09

Joe