2014-09-26 66 views
1

我使用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(在structure node)作为指针不宣类型后( struct test),仍然编译成功!上述程序编译后的印刷只是一个警告如下:

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

现在我的疑问是,为什么编译器不产生不声明structure test错误?

回答

6

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

,这将是更加清晰考虑一个简单的例子

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

在这个结构指针旁边还指出,不完全类型struct node由于结构的定义,只会在大括号之后完成。

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

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

至于指针本身然后(C标准,6.2.5类型,第#21)

A pointer type is a complete object type. 

约在结构本身(6.7.2.1结构和联合说明符,第#8 )

8一个结构声明列表的在 结构 - 或联合说明符的存在声明新的类型,翻译 单元内。 struct-declaration-list是结构或联合的成员的一系列声明。如果结构声明列表 不包含任何命名成员,没有匿名结构,也没有匿名联合,则行为是未定义的。 类型是不完整的,直到 紧接在终止列表之后,并且此后完成

1

根据explicit type conversion部从cppreference:

此外,C样式转换符号被允许从铸造到,和指针不完全类类型之间 。如果expression和 new_type都是指向不完全类类型的指针,则不指定 是否选择static_cast或reinterpret_cast。

struct test*是指向不完整类型的指针。 struct test是一个前置声明,正在引入main的本地范围。