Proper way to initialize a string in C

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

    Global variables are initialized with default values by a compiler, but local variables must be initialized.

    0 讨论(0)
  • 2021-02-01 09:11

    It depends entirely on how you're going to use it. In the following, it makes more sense not to initialize the variable:

    int count;
    while ((count = function()) > 0)
    {
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-01 09:14
    static const char str[] = "str";
    

    or

    static char str[] = "str";
    
    0 讨论(0)
  • 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.
    0 讨论(0)
  • 2021-02-01 09:20

    By proper you mean bug free? well, it depends on the situation. But there are some rules of thumb I can recommend.

    Firstly, note that strings in C are not like strings in other languages.

    They are pointers to a block of characters. The end of which is terminated with a 0 byte or NULL terminator. hence null terminated string.

    So for example, if you're going to do something like this:

    char* str;  
    gets(str);
    

    or interact with str in any way, then it's a monumental bug. The reason is because as I have just said, in C strings are not strings like other languages. They are just pointers. char* str is the size of a pointer and will always be.

    Therefore, what you need to do is allocate some memory to hold a string.

    /* this allocates 100 characters for a string 
       (including the null), remember to free it with free() */
    char* str = (char*)malloc(100);
    str[0] = 0;
    
    /* so does this, automatically freed when it goes out of scope */
    char str[100] = "";
    

    However, sometimes all you need is a pointer.
    e.g.

    /* This declares the string (not intialized) */
    char* str;
    
    /* use the string from earlier and assign the allocated/copied
       buffer to our variable */
    str = strdup(other_string);
    

    In general, it really depends on how you expect to use the string pointer. My recommendation is to either use the fixed size array form if you're only going to be using it in the scope of that function and the string is relatively small. Or initialize it to NULL. Then you can explicitly test for NULL string which is useful when it's passed into a function.

    Beware that using the array form can also be a problem if you use a function that simply checks for NULL as to where the end of the string is. e.g. strcpy or strcat functions don't care how big your buffer is. Therefore consider using an alternative like BSD's strlcpy & strlcat. Or strcpy_s & strcat_s (windows).

    Many functions expect you to pass in a proper address as well. So again, be aware that

    char* str = NULL;
    strcmp(str, "Hello World");
    

    will crash big time because strcmp doesn't like having NULL passed in.

    You have tagged this as C, but if anyone is using C++ and reads this question then switch to using std::string where possible and use the .c_str() member function on the string where you need to interact with an API that requires a standard null terminated c string.

    0 讨论(0)
提交回复
热议问题