How to initialize static pointer with malloc in C?

后端 未结 5 600
臣服心动
臣服心动 2020-12-17 22:27

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

5条回答
  •  爱一瞬间的悲伤
    2020-12-17 23:05

    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.

提交回复
热议问题