将两个不同的结构传递到相同的函数中

use*_*109 4 c struct arguments function

我有2个不同大小的结构,我想有一个功能,我可以将它们传入.但是,我不知道如何定义函数的参数来接受2个不同的结构.

我的结构如下

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);
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

不幸的是,C中不相关结构的唯一选择是将指针传递给无类型的结构(即as void*),并传递"侧面"类型,如下所示:

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);
Run Code Online (Sandbox Code Playgroud)

但是,这种方法非常容易出错,因为编译器无法为您进行类型检查.


Joe*_*Joe 4

这真的不可能。您可以创建一个包含两个结构体和某种标识符的联合。然后,您传入联合并使用标识符来计算其中包含哪个结构。

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;
    }
}
Run Code Online (Sandbox Code Playgroud)