C语言 如何在单个函数中传递不同的结构作为参数



我有2个结构名称struct1, struct2。我也有一个操作函数名为"myFun">

void myFun(/一个指针参数/)

我有一个设置标志,如果设置标志是1,我需要传递struct1指针作为myFun参数如果设置标志为0,我需要传递myFun参数作为struct2指针。

这是可能的,我怎么做这个

我尝试的示例(不工作)代码如下所示。

#include <stdio.h>
#include <string.h>
typedef struct struct1{
int a;
int b;
}struct1;
typedef struct struct2{
int a;
}struct2;
void myFun(void *arg, int select)
{
if(select)
{
arg->a = 10;
arg->b = 20;
}
else
{
arg->a = 100;
}
}
int main() {
// Write C code here
int select = 0;
struct1 t1;
struct2 t2;
printf(enter the select option 0 or 1);
scanf("%d",select);
if(select)
{
myFun((void *)&t1,select);
}
else
{
myFun((void *)&t2,select);
}
return 0;
}

使用强制转换:

if(select)
{
struct1* ptr = (struct1*)(arg);
ptr->a = 10;
ptr->b = 20;
}
else
{
struct2* ptr = (struct2*)(arg);
ptr->a = 100;
}
}

实际上,void*的显式强制转换在C中并不需要,因为它在c++中是必要的。所以这也足够了:

if(select)
{
struct1* ptr = arg;
ptr->a = 10;
ptr->b = 20;
}
else
{
struct2* ptr = arg;
ptr->a = 100;
}
}

最新更新