【问题标题】:How does the struct of a linked list know the type of next pointer of its own type?链表的结构如何知道自己类型的 next 指针的类型?
【发布时间】:2015-03-16 07:37:26
【问题描述】:
struct node
{
    int     data;
    node*   pointerToNextNode;
};

这里pointerToNextNodestruct node的类型,在struct里面声明。 结构体如何知道它自己类型的下一个指针的类型 - 当它本身还没有形成时?

没有使用关键字extern。这是如何工作的?

【问题讨论】:

  • 如果 private 被用作访问说明符,那么 C 就不能这样工作。
  • @ArjunSreedharan 抱歉,打错字了。

标签: c struct linked-list


【解决方案1】:

不需要知道结构,知道类型名就足够了,即struct node——并且已经定义好了。

通过前向类型声明可以获得相同的结果:

struct node;            // declare the struct not defining it
struct node *pointer;   // declare variable

void foo()
{
    if(pointer != NULL)        // OK, we use the pointer only
        if(pointer->x == 0)    // invalid use - struct contents unknown yet
            return;
}

struct node {           // supply a definition
    int x;
};

void bar()
{
    if(pointer != NULL)
        if(pointer->x == 0)    // OK - struct contents already known
            return;
}

【讨论】:

    【解决方案2】:

    这里pointerToNextNodestruct node的类型

    不,不是。它的类型为struct node *

    struct node* pointerToNextNode;struct node 类型的指针 变量分配内存。
    它不会为struct node 分配内存,因此,到目前为止,它不需要知道struct node 的大小和表示形式。只有(数据)类型名称就足够了。

    另外,值得一提的是,如果没有 typedefnode* pointerToNextNode; 应该是无效的。应该像下面这样写

    typedef struct node node; 
    
    struct node 
    { 
        int data; 
        node* pointerToNextNode; 
    };
    

    顺便说一句,private: 不是 C 的东西,如果我没记错的话。

    【讨论】:

    • 是的,private 是错字。对不起。您能否展示使用 typedef 编写该代码的正确方法?
    • @TheIndependentAquarius 试试typedef struct node node; struct node { int data; node* pointerToNextNode; };
    • 你不应该为结构体的 typedefs 烦恼。他们没用。它们只会让您免于在少数地方写 struct,这是不应该丢失的信息。
    【解决方案3】:

    对我来说,这不是使用 CC 编译的——正是因为你所说的。 您必须使用struct node * 让编译器知道您需要内存用于指针

    【讨论】:

      猜你喜欢
      • 2017-11-10
      • 2012-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-30
      • 2012-03-27
      • 1970-01-01
      相关资源
      最近更新 更多