Proper way to initialize a string in C

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

    this is a general question about c variables not just char ptrs.

    It is considered best practice to initialize a variable at the point of declaration. ie

    char *str = NULL;
    

    is a Good Thing. THis way you never have variables with unknown values. For example if later in your code you do

    if(str != NULL)
     doBar(str);
    

    What will happen. str is in an unknown (and almost certainly not NULL) state

    Note that static variables will be initialized to zero / NULL for you. Its not clear from the question if you are asking about locals or statics

提交回复
热议问题