Shankhadeep Mukerji Shankhadeep Mukerji - 2 months ago 9
C Question

Not able to declare a dynamic array of structs

I am getting compilation error for the following code. I have tried my best, but cannot figure it out. Any help will be appreciated.

#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);
}


I am getting the error in GCC:


struct_check.c:9:
error:
‘node’
undeclared here (not in a function)

Answer

First of all, syntactically, you need to change

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

to

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

because, node itself is not a type, unless you use a typedef to create one.

That said,

  • You cannot have a statement to be executed in global scope, move that inside some function.
  • You never seem to make use of p, anywhere.
  • You're using pin_2 and pin_0 uninitialized, that invokes undefined behavior. You need to make those pointers point to some valid memory before you can dereference them.
  • void main() is obsolete as per the latest standard, and for a hosted environment, the conforming signature will be int main(void), at aleast.
  • You can write a more robust statement by using the style struct node *p = malloc ( N *sizeof(*p));