Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global struct in c (initializer element is not a compile-time constant)

I am pretty new to C and I have some problems.

I have the following struct definition:

struct env {
  struct env *next;
  char varName[8];
  int n;
};

I want to create multiple of those structs eventually in some of my functions so I created a function to do that :

struct env *mkEnv(char c[8] , int value , struct env *toadd){
    struct env *enviroment = malloc(sizeof(struct env));
    enviroment->n = value;
    enviroment->next = toadd;
    strcpy(enviroment->varName , c);
    return enviroment;
}

I want to create a struct like this globally that is constant with some constant values and initially have the pointer to the next structure NULL.

So I did something like this :

    //not in a function
    struct env *list = mkEnv("pot" , 0 , NULL);

    //Beginning of a function
    int eval(struct expression *exp){
        ... // code here that might add a new structure to the pointer of list
    }

I get the following error however :

evalexp.c:116:20: error: initializer element is not a compile-time constant struct env *list = mkEnv("p" , 0 , NULL);

I understand what this error means after googling about the error message but is there a way to create a structure somewhere outside of a function without getting this compilation error?

To make it more clear : I want to create a structure as defined above (as if it was the head of a list). so that all my functions can access and add stuff to it. That is parsing it as a list and/or adding new elements in that list.

Thanks in advance!

like image 577
Jetmax Avatar asked Jan 28 '26 05:01

Jetmax


2 Answers

A function cannot be called in file scope.

You must use constant values and define an actual struct variable:

struct env lists = { NULL , "pot" , 0 };
struct env *list = &lists;

Now the pointer list is initialized and can be used, but beware that it wasn't created with malloc, so it cannot be freed or reallocated.

like image 68
2501 Avatar answered Jan 30 '26 20:01

2501


Define the variable, and initialize it in main.

struct env *list;

int main() {
    list = mkEnv("pot" , 0 , NULL);
    ....
}

Sometimes libraries make you call a function to initialize the library before any of its functions should be used. Giving values to global variables that they use is one of the reasons why they do that.

like image 20
Joni Avatar answered Jan 30 '26 21:01

Joni