Proper way to initialize a string in C

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

    I'm wonder, what is the proper way of initializing a string?

    Well, since the second snippet defines an uninitialized pointer to string, I'd say the first one. :)

    In general, if you want to play it safe, it's good to initialize to NULL all pointers; in this way, it's easy to spot problems derived from uninitialized pointers, since dereferencing a NULL pointer will yield a crash (actually, as far as the standard is concerned, it's undefined behavior, but on every machine I've seen it's a crash).

    However, you should not confuse a NULL pointer to string with an empty string: a NULL pointer to string means that that pointer points to nothing, while an empty string is a "real", zero-length string (i.e. it contains just a NUL character).

    char * str=NULL; /* NULL pointer to string - there's no string, just a pointer */
    const char * str2 = ""; /* Pointer to a constant empty string */
    
    char str3[] = "random text to reach 15 characters ;)"; /* String allocated (presumably on the stack) that contains some text */
    *str3 = 0; /* str3 is emptied by putting a NUL in first position */
    

提交回复
热议问题