2

I am just learning C. I'm trying to compile this code:

int *p = malloc(sizeof(int));

linked-list.c:12:10: error: initializer element is not a compile-time constant int *p = malloc(sizeof(int)); ^~~~~~~~~~~~~~~~~~~ 1 error generated.

What am I doing wrong here? I'm guessing it is talking about int not being a compile-time constant. Is that because it doesn't know the size of an int on my system? Most of the other answers on sa for this question seem like they really are using run-time variables as initializers but why is int a run time variable?

BigBoy1337
  • 4,735
  • 16
  • 70
  • 138
  • 1
    Does this answer your question? [initializer element is not a compile-time constant with malloc](https://stackoverflow.com/questions/63303468/initializer-element-is-not-a-compile-time-constant-with-malloc) – cocomac Aug 24 '22 at 22:21
  • 1
    @cocomac yes it does – BigBoy1337 Aug 24 '22 at 22:24

1 Answers1

5

You can't initialize global variables with non-constant values. Do the initialization inside a function.

int *p;

int main(void)
{
    p = malloc(sizeof(int));
    free(p);
    return 0;
}
Carl Norum
  • 219,201
  • 40
  • 422
  • 469