error: initializer element is not constant [How to Solve]

1. Background

C language compilation error: error: initializer element is not constant. The error code is as follows:

    char *info = (char *)malloc(len);
    static char *info_t = info;

The above error is caused by trying to initialize a static variable with the memory pointer allocated by malloc.

2. Error reason

Static variable is a global variable. The value of the global variable cannot be determined at compile time, but at run time (compilation principle). Therefore, the global variable cannot be initialized directly with the return value of malloc at the time of declaration. Replace with the following:

    char *info = (char *)malloc(len);
    static char *info_t; 
    info_t = info;

Compilation passed.


Read More: