C语言指向内容不确定的结构体如何用指针实现
C语言指向内容不确定的结构体怎么用指针实现
比如有两个结构体
typedef struct Msg1
{
int a;
float b;
int c;
}M1;
typedef struct Msg2
{
char a[20];
int b;
}M2;
一个函数执行完毕后可能返回Msg1或Msg2结构体,怎么让返回值用指针实现指向不定结构体?
------解决方案--------------------
用void*返回,用的时候再强制转换即可,例如M1* p = (M1*)fun();
------解决方案--------------------
转换成void*返回,不过要想确认返回的是哪个个类型,必须还有加标识,可以参考以下两种方法
(1)可设置一个全局变量,在返回的函数内对于返回不同的结构类型,设置不同的标识,
(2)在每个结构体内,最开始部分加一个字节,用于标识它本身
------解决方案--------------------
------解决方案--------------------
比如有两个结构体
typedef struct Msg1
{
int a;
float b;
int c;
}M1;
typedef struct Msg2
{
char a[20];
int b;
}M2;
一个函数执行完毕后可能返回Msg1或Msg2结构体,怎么让返回值用指针实现指向不定结构体?
C
指针
struct
------解决方案--------------------
用void*返回,用的时候再强制转换即可,例如M1* p = (M1*)fun();
------解决方案--------------------
转换成void*返回,不过要想确认返回的是哪个个类型,必须还有加标识,可以参考以下两种方法
(1)可设置一个全局变量,在返回的函数内对于返回不同的结构类型,设置不同的标识,
(2)在每个结构体内,最开始部分加一个字节,用于标识它本身
------解决方案--------------------
typedef struct Msg1
{
int a;
float b;
int c;
}M1;
typedef struct Msg2
{
char a[20];
int b;
}M2;
typedef struct Msg
{
int tag;//区分使用的是哪个结构体
union
{
M1 m1;
M2 m2;
};
}Msg;
------解决方案--------------------
#include <stdio.h>
#include <string.h>
typedef struct Msg1 {
int a;
float b;
int c;
} M1;
typedef struct Msg2 {
char a[20];
int b;
} M2;
void *fun(int *t) {
static M1 m1;
static M2 m2;
static a=2;
a=3-a;
*t=a;
if (a==1) {
m1.a=1;
m1.b=0.5f;
m1.c=2;
return &m1;
} else {//a==2
strncpy(m2.a,"abcdefghijklmnopqrstuvwxyz",19);(m2.a)[19]=0;
m2.b=3;
return &m2;
}
}
int main() {
M1 *p1;
M2 *p2;
int i,f;
void *pv;
for (i=0;i<2;i++) {
pv=fun(&f);
if (f==1) {
p1=(M1 *)pv;
printf("p1->a==%d,p1->b==%g,p1->c==%d\n",p1->a,p1->b,p1->c);