Click here to Skip to main content
15,123,923 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can we initialize the variables globally?

Because I am getting error like this:
main.c:6:3: error: initializer element is not constant

What I have tried:

C++
#include <stdio.h>
#include<stdlib.h>
struct Node{
    int a;
    int b;
}*a;
a=(struct Node*)malloc(sizeof(struct Node));
int main()
{
    printf("Hello world");
    return 0;
}
Posted
Updated 22-Jul-21 3:48am

It's not inside a function, which means it has to be an initializer - which is assigned only when the item is declared - which means it must be a constant value at compile time, which malloc cannot be.

Move the line inside the main function and it'll work:
C
#include <stdio.h>
#include<stdlib.h>
struct Node{
    int a;
    int b;
}*a;
int main()
{
    a=(struct Node*)malloc(sizeof(struct Node));
    printf("Hello world");
    return 0;
}
   
No, you cannot do that (calling a function outside other functions).
Typically you do
C
#include <stdio.h>
#include<stdlib.h>
struct Node
{
    int a;
    int b;
} * a = NULL;

int main()
{
  if ( ! a)
    a=(struct Node*)malloc(sizeof(struct Node));

  printf("Hello world");

  if (a)
    free(a);

  return 0;
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900