error: initializer element is not Constant

Asked

Viewed 1,504 times

4

I’m trying to declare this buffer overall and when compiling it presents the following error

error: initializer element is not Constant

char    *ls_buffer_PPouAUT =    malloc(5120*sizeof(char));

How can I fix it?

1 answer

6


Place the variable inside a function.

Don’t use anything global, it’s unnecessary in almost every case. In cases that might be useful you need to know what you’re doing well, understand all the implications, you’re probably using it inadvertently.

Of course, it’s still possible declare the global variable and initialize it within the function, ideally just at the beginning of the main() not to be in invalid state. But avoid, it is better. Create a local variable and pass it as an argument to other functions or store it in a structure that makes sense.

Global variables are initialized during compilation. You cannot run the function malloc() at that time, during compilation can only have constant values, so they can be placed inside the generated executable.

As this value can only be known during execution, it needs to be at one point within the application’s execution flow. Only functions have execution flow.

It is guaranteed that sizeof char be 1, so there’s no point in wearing this.

  • thank you, I will try to do this, initialize within the function

  • The *sizeof(char) is completely unnecessary.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.