How to resolve: error: initializer element is not constant

Sometimes during complex programing, there are chances we make some mistakes during hurry to write and complete the program so that we can test the features, in somewhat similar occasion, we faced an error during compilation as, “error: initializer element is not constant” , now as mentioned, if we have written multiple lines during coding and before compilation, it becomes difficult to remember we initialized which variable and where..?

So, lets recreate similar error, with a very basic C program as below,

 $ vim helloerror.c 
[bash] #include <stdio.h> #include <stdlib.h> int *var = (int *)malloc(sizeof(int)); int main(int argc, char **argv) { *var = 10; printf("var is %d\n", *var); return 0; } [/bash]
 $ gcc -o helloerror helloerror.c 
 $ ./helloerror
helloerror.c:4:12: error: initializer element is not constant
 int *var = (int *)malloc(sizeof(int));

so, we got the mentioned error and during compilation, if the compiler is latest, it also shown the line of error.

Now, if we relooked at the code, we have a global integer pointer “var” and we are assigning a memory to it by calling malloc, ideally this looks OK, but the catch is this is a “GLOBAL” variable, outside all the functions, so the program execution only initialises these variables once, so these are expected to be constants and not changing like we have done an assigned of it to memory returned by malloc.

SO, to avoid this error, always make sure all global variables are assigned with constants.

Now, lets rewrite this program to make sure error is gone,

[bash] #include <stdio.h> #include <stdlib.h> int *var = NULL; int main(int argc, char **argv) { var = (int *)malloc(sizeof(int)); *var = 10; printf("var is %d\n", *var); return 0; } [/bash]

Changes are done in “int *var = NULL;” and moving malloc statement inside main.

Leave a Comment