本文介绍了将两个不同的结构传递给相同的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2种不同大小的结构,并且我希望有一个函数可以将它们传递给其中.但是,我不知道如何定义函数的参数以接受2种不同的结构.
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.
我的结构在下面
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);推荐答案
不幸的是,C语言中不相关结构的唯一选择是将指针传递给未类型化的结构(即void*),并在类型上传递类型侧面",像这样:
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.
更多推荐
将两个不同的结构传递给相同的函数
发布评论