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
If it is file static, then you should provide a public function in that file that will initialize that static.
void initialize () {
if (p == 0) p = malloc(sizeof(*p));
}
Or, you can use a static function instead of a static variable. It costs you a check per access though:
static int * p () {
static int * p_;
return p_ ? p_ : (p_ = malloc(sizeof(*p_)));
}
For an integer type, this seems a little silly, but if p were some more complex type that required a more complicated initialization sequence than just the return value of malloc(), then it might make sense to have something like this.