2016-12-14 72 views
1
int main(void) 
{ 
    struct a 
    { 
     struct b* x; 
    }; 
} 

我定义struct a为包含指针xstruct b而不定义struct b。我期待着一个错误。即使通过包含-Wall,我也没有从编译器中得到什么。有没有对此的解释?为什么一个结构体中可能包含一个指向未定义的另一个结构体的指针?

+0

它知道如何做指针。但是你不能在不定义'struct b'的情况下解引用它('* x')。 – e0k

+0

在上下文中,'struct b'是一个不完整或不透明的类型。他们其实很有用。 –

回答

2

这只是一种标准的语言功能。 struct b现在是一个不完整的类型。用不完整的类型可以做很多事情。但有一点可以做的是声明不完整类型的指针。

您将可以通过提供完整声明struct b来完成该类型。之后它将成为一个普通的结构类型。

+0

当我删除'*',我得到了'错误:字段'x'有不完整的类型'。这是否意味着包含不完整类型是非法的,但是包含指向不完整类型的指针是合法的?这怎么可能有用? –

+0

@W。朱:是的,声明不完整类型的指针是合法的,但是声明不完整类型的对象是非法的。它对于许多不同的目的非常有用,比如实现隐藏(不透明类型)。事实上,不依赖这个特性就不可能声明一个简单的链表。再次,请记住,不完整类型稍后会在完全声明时(以及在何处)变为完整类型。 – AnT

2

你有什么是incomplete type,这样的类型的指针是完全正确的,但除非你完成它否则不能实例化。

2.7 Incomplete Types

You can define structures, unions, and enumerations without listing their members (or values, in the case of enumerations). Doing so results in an incomplete type. You can’t declare variables of incomplete types, but you can work with pointers to those types.

struct point; 

At some time later in your program you will want to complete the type. You do this by defining it as you usually would:

struct point { 
    int x, y; 
}; 

This technique is commonly used to for linked lists:

struct singly_linked_list { 
    struct singly_linked_list *next; 
    int x; 
    /* other members here perhaps */ 
}; 
struct singly_linked_list *list_head; 
+0

是否意味着'struct a'包含一个指向空结构的指针? –

+0

@ W.Zhu。对不起,前面的答案,看我更新的答案 – smac89

0

因为编译器分配结构,因为它知道一个指针的大小,但你不能使用x因为编译器将不知道如何取消引用指针除非有结构的定义。

您可以通过使用前置声明利用这一点,你可以声明一个未知struct类型的指针和避免包括仅从而改善编译时间和精力结构的可能大的头文件。

相关问题