今天突然看到一个结构体互相作为成员变量的问题,感觉很有趣。有人说这无异于自己揪着自己的头发把自己提起来。觉得这个比喻很有趣。
然后自己尝试做了实验;
#include <stdio.h>
typedef struct A testA;
typedef struct B testB;
struct A{
testB b;
char namea;
};
struct B{
testA a;
char nameb;
};
int main(int argc,char ** args)
{
testA testa;
testB testb;
return 0;
}
[root@localhost hi]# gcc teststruct.c -o teststruct
teststruct.c:5: 错误:字段‘b’的类型不完全
这样的话 A结构的sizeof就是无穷了,因为A结构会间接循环调用A,不想头文件那样有宏的控制,可以避免循环调用
有一个前提是结构体的大小应该是固定的,要不然怎么能成为结构呢。所以这个时候可以使用指针,指针的大小是固定的,指针不能初始化实例,但是能指向结构B。
#include <stdio.h>
typedef struct A testA;
typedef struct B testB;
typedef struct A* pA;
typedef struct B* pB;
struct A{
pB b;
char namea;
};
struct B{
pA a;
char nameb;
};
int main(int