【问题标题】:Strange behavior of "node"“节点”的奇怪行为
【发布时间】:2012-12-22 22:38:04
【问题描述】:

我很困惑!尝试创建动态链表并希望通过“malloc”函数分配标题。从我下面的代码编译器给出2个错误:

in main: [Error] node' undeclared (first use in this function) and **In functionnewnode':** [Error] `node' undeclared (第一次在这个函数中使用)

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

struct node{
    int a,b,c,d;
    struct node *next;
};

struct node * newnode(int, int, int, int);

int main(){
    struct node *header;
    header=(struct node *)malloc(sizeof(node));
    int a,b,c,d;
    a=11;
    b=2;
    c=4;
    d=5;
    header->next=newnode(a,b,c,d);
    printf("\n\n");
    system("PAUSE");
    return 0;
}

struct node * newnode(int aa, int bb, int cc, int dd)
{
    struct node *temp;
    temp=(struct node*)malloc(sizeof(node));
    temp->a =aa;
    temp->b =bb;
    temp->c =cc;
    temp->d =dd;
    temp->next=NULL;
    return temp;
}

感谢任何建议!谢谢!

【问题讨论】:

    标签: c malloc


    【解决方案1】:

    没有类型node。您输入了struct node,这就是您需要传递给sizeof 运算符的那个。

    【讨论】:

      【解决方案2】:

      首先,正如@icepack 已经指出的那样,该类型被命名为struct node,而不是node。因此,sizeof(node) 无法编译。除了sizeof 的那两个地方之外,您在代码中的任何地方都小心翼翼地使用了struct node

      其次,考虑使用

      T *p = malloc(n * sizeof *p); /* to allocate an array of n elements */
      

      内存分配的习惯用法。例如。在你的情况下

      temp = malloc(sizeof *temp);
      

      即不要转换malloc 的结果,而是更喜欢将sizeof表达式 一起使用,而不是与类型名称一起使用。类型名称属于声明。其余代码应尽可能与类型无关。

      【讨论】:

        【解决方案3】:

        正如前面的答案所提到的,在引用您的结构时,您必须使用 struct node

        但是,如果您只想使用声明性名称节点,您可以执行以下操作:

        typedef struct _node{
            int a,b,c,d;
            struct _node *next;
        }  node;
        

        这里你不需要在引用node之前使用struct

        编辑:语法错误

        【讨论】:

          猜你喜欢
          • 2015-06-09
          • 2017-04-14
          • 2018-08-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-05
          • 2021-06-27
          • 2012-07-19
          相关资源
          最近更新 更多