C语言结构体的前向声明,以及结构体嵌套const结构体成员的问题

如果你在声明一个结构体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;
}

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值