I\'m trying to initiate a static variable (inside a function) with malloc in C, but I\'m getting the \"initializer not constant error\". I know that I can\'t initiate a stat
Assuming you want function-static variables:
int foo(void) {
static int b=1;
static int *p;
if (b) {
p = malloc(sizeof(int));
b = 0;
}
...
}
You can use NULL value for p as a check, as long as you know it will never be NULL
after the first call.
Remember to check for errors in malloc; it is a runtime allocation, and should also be freed when it will not be needed anymore.