【问题标题】:Typedef's and nodesTypedef 和节点
【发布时间】:2016-04-18 20:50:13
【问题描述】:

此代码应该构建一个包含从 0 到 20 的整数的简单链表。当我为程序中的每个节点实例编译代码时,我不断收到错误消息:unknown type name 'node'。我不确定是否必须定义它们或代码中存在更大的缺陷。

#include<stdio.h>
#include<stdlib.h>

int main()  {
    int i;
    struct node *first=NULL;
    for(i=1;i<=20;i++)
        first=insertrear(first,i);
    dispnodes(first);
    sum(first);

return 0;
}
typedef struct node {
    int data;
    struct node *link;
};

 node* getnode(node *temp,int i) {
    temp=(node*)malloc(sizeof(node));
    temp->data=i;
    temp->link=NULL;
    return temp;
}
node* insertrear(node *first,int a) {
    node *temp=NULL,*i;
    temp= getnode(temp,a);
    if(first==NULL) {
        first=temp;
        return first;
    }

    for(i=first;i->link!=NULL;i=i->link);
        i->link=temp;
        return first;
}

void dispnodes(node *first) {
    int j;
    if(first==NULL) {
        printf("\nlist empty");
        return;
    }
    node *i;
    for(i=first,j=0;i!=NULL;j++,i=i->link)
        printf("\nNode #%d contains %d  ",j,i->data);
}

void sum(node *first)   {
    node *i;
    int total=0;
    for(i=first;i!=NULL;i=i->link)
        total+=i->data;
    printf("\nThe sum total of all nodes in this list is %d",total);
}

【问题讨论】:

    标签: c linked-list nodes


    【解决方案1】:

    您要么需要为 typedef struct 节点指定标签,要么不 typedef struct 节点。

    你使用它的方式,你可以做到以下。

    /* Forward declare typedef _node to node */
    typedef struct node_ node;
    
    /* Define struct node_ */
    struct node_ {
        int data;
        node *link;
    };
    

    您应该在main() 上方有前向声明,以便您也可以在那里使用它。

    【讨论】:

    • struct _node 是否与 C11 7.1.3 保留标识符冲突:“所有以下划线开头的标识符始终保留用作普通和标记名称空间中具有文件范围的标识符。”?
    【解决方案2】:
    typedef struct node {
        int data;
        struct node *link;
    }node;
    
    int main()  {
        int i;
        struct node *first=NULL;
        for(i=1;i<=20;i++)
            first=insertrear(first,i);
        dispnodes(first);
        sum(first);
    
    return 0;
    }
    

    【讨论】:

    • 其他东西还需要在main前声明!
    【解决方案3】:

    有两点需要修改:

    1. 您必须声明 struct ,typedef 以及您在 main 函数之前调用的所有函数。编译器应在遇到它们之前提供声明。

    2. 另外你还没有为typedef 提供标签来构造node,你可以这样做:

      typedef struct node {
          int data;
          struct node *link;
      } Node ;
      

      或者使用struct node而不是node来声明struct node类型的变量

    修改后的代码如下:

    typedef struct node
    {
      int data;
      struct node *link;
    } Node ;
    
    void dispnodes(Node *first);
    node* insertrear(Node *first,int a);
    void sum(Node *first);
    
    int main()  {
        int i;
        struct node *first=NULL;
        for(i=1;i<=20;i++)
            first=insertrear(first,i);
        dispnodes(first);
        sum(first);
    
        return 0;
    }
    // rest of the code
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-24
      • 2019-01-21
      相关资源
      最近更新 更多