【问题标题】:Compiler not showing error on declaring pointer of undefined type编译器在声明未定义类型的指针时未显示错误
【发布时间】:2014-09-26 06:58:02
【问题描述】:

我使用 gcc 编译器编译了以下 c 代码:

#include <stdio.h>

struct node{
        int info;
        struct test* next;
};

int main()
{
        struct node start;
        struct node* p;
        start.info = 2;
        start.next = (struct test*)&start;
        printf("start.next = %p \n",start.next);
        p = start.next;
        printf("p->info = %d\n",p->info);
}

但令我惊讶的是,在将next(in structure node) 声明为指向未声明类型(struct test) 的指针后,编译仍然成功!!!编译上述程序后,仅打印如下警告:

test.c:15:4: warning: assignment from incompatible pointer type [enabled by default]
  p = start.next;
    ^

现在我的疑问是为什么编译器没有因为未声明 structure test 而产生错误?

【问题讨论】:

    标签: c pointers gcc declaration


    【解决方案1】:

    您的程序中没有未定义的类型。在结构 struct node 中声明了一个不完整的类型 struct test。 您可以使用指向不完整类型的指针。

    考虑一个简化的例子会更清楚

    struct node{
            int info;
            struct node* next;
    };
    

    在这个结构体中,next 也指向不完整的类型struct node,因为结构体定义只有在右大括号之后才会完成。

    一个更有趣的例子。 void * 类型在 C 程序中的使用非常不同。但是根据 C 标准(6.2.5 类型,p.#19)

    19 void 类型包含一组空值; 这是一个 无法完成的不完整对象类型。

    至于指针本身(C 标准,6.2.5 类型,p.#21)

    A pointer type is a complete object type.
    

    关于结构本身(6.7.2.1 结构和联合说明符,p.#8)

    8 结构声明列表的存在 struct-or-union-specifier 在翻译中声明一个新类型 单元。 struct-declaration-list 是一系列声明 结构或工会的成员。如果结构声明列表 不包含命名成员,不包含匿名结构,也不包含匿名 工会,行为未定义。 类型不完整,直到 紧跟在终止列表的 } 之后,并完成 此后。

    【讨论】:

      【解决方案2】:

      在 cppreference 的 explicit type conversion 部分下:

      此外,C 风格的转换表示法允许转换 from、to 和 在指向不完整类类型的指针之间。如果表达式和 new_type 是指向不完整类类型的指针,未指定 是否选择了 static_cast 或 reinterpret_cast。

      struct test* 是一个指向不完整类型的指针。 struct test 是一个前向声明,它被引入到 main 的本地范围中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-21
        • 1970-01-01
        • 1970-01-01
        • 2014-08-09
        • 1970-01-01
        • 2019-03-22
        • 1970-01-01
        相关资源
        最近更新 更多