Proper way to initialize a string in C

后端 未结 11 1258
臣服心动
臣服心动 2021-02-01 08:23

I\'ve seen people\'s code as:

char *str = NULL;

and I\'ve seen this is as well,

char *str;

I\'m wonder, what

11条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-01 09:14

    Don't initialise all your pointer variables to NULL on declaration "just in case".

    The compiler will warn you if you try to use a pointer variable that has not been initialised, except when you pass it by address to a function (and you usually do that in order to give it a value).

    Initialising a pointer to NULL is not the same as initialising it to a sensible value, and initialising it to NULL just disables the compiler's ability to tell you that you haven't initialised it to a sensible value.

    Only initialise pointers to NULL on declaration if you get a compiler warning if you don't, or you are passing them by address to a function that expects them to be NULL.

    If you can't see both the declaration of a pointer variable and the point at which it is first given a value in the same screen-full, your function is too big.

提交回复
热议问题