Proper way to initialize a string in C

后端 未结 11 1241
臣服心动
臣服心动 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:17

    an unitialized pointer should be considered as undefined so to avoid generating errors by using an undefined value it's always better to use

    char *str = NULL;
    

    also because

    char *str;
    

    this will be just an unallocated pointer to somewhere that will mostly cause problems when used if you forget to allocate it, you will need to allocate it ANYWAY (or copy another pointer).

    This means that you can choose:

    • if you know that you will allocate it shortly after its declaration you can avoid setting it as NULL (this is a sort of rule to thumb)
    • in any other case, if you want to be sure, just do it. The only real problem occurs if you try to use it without having initialized it.

提交回复
热议问题