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

编程入门 行业动态 更新时间:2024-10-09 21:19:57
本文介绍了将两个不同的结构传递给相同的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有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.

更多推荐

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

本文发布于:2023-11-29 04:23:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645262.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   两个   结构

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!