无法声明动态结构数组

时间:2016-10-03 10:01:04

标签: c struct compiler-errors dynamic-memory-allocation

我收到以下代码的编译错误。我尽了最大努力,但无法理解。任何帮助将不胜感激。

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

#define N 100

int counter=0;
struct node {
    int value; };
struct node *p = (struct node  *) malloc (N*sizeof (node));

void main()
{

    int a = 5, b=6;
        struct node * c = 0;
    c = add(a,b); 
}

void add(int m, int n)
{
    struct node * pin_1;
        struct node * pin_2;
        struct node * pin_0;
    pin_0->value = m;
    pin_1->value = n;
    pin_2->value = m + n;
    counter++;
    printf("value of out is %d /n", pin_2->value);       
}

我在GCC中收到错误:

  

struct_check.c:9:错误:‘node’未声明此处(不在函数中)

1 个答案:

答案 0 :(得分:4)

首先,从语法上讲,你需要改变

  struct node *p = (struct node  *) malloc (N*sizeof (node));

  struct node *p = malloc (N*sizeof ( struct node));

因为node本身不是类型,除非您使用typedef创建一个。

那就是说,

  • 你不能在全局范围内执行语句,在一些函数中移动它。
  • 您似乎永远不会在任何地方使用p
  • 您正在使用pin_2pin_0未初始化,即调用undefined behavior。在取消引用它们之前,你需要让这些指针指向一些有效的内存。
  • 根据最新标准,
  • void main()已过时,对于托管环境,符合条件的签名将为int main(void),at aleast。
  • 您可以使用样式struct node *p = malloc ( N *sizeof(*p));
  • 编写更健壮的语句
相关问题