无法声明结构的动态数组

Not able to declare a dynamic array of structs

我收到以下代码的编译错误。我已尽力而为,但无法弄清楚。任何帮助将不胜感激。

#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: error: ‘node’ undeclared here (not in a function)

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

  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)
  • 您可以使用 struct node *p = malloc ( N *sizeof(*p));
  • 样式编写更健壮的语句