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 
#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;
}
 $ 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.


Subscribe with Valid Email Id to receive updates in Inbox. ( Secured by Google FeedBurner )

   


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,

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

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

lynxbee_ezoic

Leave a Comment

Android Android Build system Android Commands Android Java Applications Application Libraries Application Stack / User Interface Bash / Shell Scripts Bluetooth driver Cloud Technologies Commands and Packages Compilation Content Management System Core Kernel C Programs Development & Build Development, Debugging and Performance Tools Development Environment Setup Django & REST Api Errors & Failures Git Hardware Platforms HTML JAVA Programs Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Multimedia Audio, Video, Images NDK / Middleware / HAL OS Concepts PHP Programming Languages Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Source Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Web design and development Website Hosting Wordpress Yocto / Bitbake / Openembedded