How to initialize static pointer with malloc in C?

后端 未结 5 596
臣服心动
臣服心动 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:06

    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.

提交回复
热议问题