0

Can someone explain me why I can't do something like that?

int* arr1 = malloc(sizeof(int));
static int* arr2 = malloc(sizeof(int));

int main() {
    return 0;
}

What is the reason that I get in this case compilation error?

initializer element is not constant

Software_t
  • 576
  • 1
  • 4
  • 13
  • Just search Global Pointer in C, you will get many posts on StackOverflow, already explaining it. Don't shower any more duplicates, please. – Abhishek Jaiswal Jul 13 '18 at 10:50
  • 3
    @AbhishekJaiswal Well, your proposed duplicate has nothing to do with the question presented here. – Kami Kaze Jul 13 '18 at 11:27

2 Answers2

8

Because malloc is a function (which returns a pointer to the allocated area) and in C you are only allowed to run code (call functions, do calculations, etc) inside a "running sequence", that's why C is a procedural language.

this is different from setting a static initial value to the variable, which will be initialized by the c runtime init before calling main()

Gustavo Laureano
  • 556
  • 2
  • 10
1

Objects defined at file scope have static storage duration.

From C Standard#6.7.9p4 [Initialization]

All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals. [emphasis mine]

H.S.
  • 11,654
  • 2
  • 15
  • 32