如果你在声明一个结构体A时,要使用一个未声明的结构体B时,该怎么办?如下:
#include <stdio.h>
typedef struct demo{
struct stu test;
const int test2;
int test3;
}demo_t;
struct stu{
const int a;
int b;
};
int main()
{
printf("Hello, World! \n");
return 0;
}
编译报错:/tmp/499466774/main.c:4:16: error: field has incomplete type 'struct stu'
struct stu test;
^
/tmp/499466774/main.c:4:12: note: forward declaration of 'struct stu'
struct stu test;
使用了未声明的类型。
这时就可以用到结构体的前向声明:
#include <stdio.h>
typedef struct stu str_t;
typedef struct demo{
const str_t* test; /*注意此处必须为指针类型,因为前向声明并没有指出该类型的大小,所以在定义时使用结构体变量无法得知该结构体的大小*/
const int test2;
int test3;
}demo_t;
struct stu{
const int a;
int b;
};
int main()
{
demo_t dem_test;
dem_test.test = (str_t *) malloc(sizeof(str_t));
//dem_test.test->b =1;
printf("Hello, World! \n");
return 0;
}
还没完呢!
有没有注意到如果此时你要给demo_t的test成员的b赋值时,根本赋值不了,因为test是const类型的结构体它的成员都是只读的,const类型在定义时就应该初始化比如 const int a =1;系统默认会给定义的变量初始化,所以const必须在定义时就初始化。
此时一个的解决方案就是你自己定义一个struct stu 的变量,让demo_t的test指针指向它,这样就不会出现问题了。
这里贴出最终的代码:
#include <stdio.h>
typedef struct stu str_t;
typedef struct demo{
const str_t* test;
const int test2;
int test3;
}demo_t;
struct stu{
const int a;
int b;
};
int main()
{
str_t *str_test;
str_test =(str_t *) malloc (sizeof(str_t));
demo_t dem_test;
dem_test.test = str_test;
printf("Hello, World! \n");
return 0;
}