Proper way to initialize a string in C

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

    Your first snippet is a variable definition with initialization; the second snippet is a variable definition without initialization.

    The proper way to initialize a string is to provide an initializer when you define it. Initializing it to NULL or something else depends on what you want to do with it.

    Also be aware of what you call "string". C has no such type: usually "string" in a C context means "array of [some number of] char". You have pointers to char in the snippets above.

    Assume you have a program that wants the username in argv[1] and copies it to the string "name". When you define the name variable you can keep it uninitialized, or initialize it to NULL (if it's a pointer to char), or initialize with a default name.

    int main(int argc, char **argv) {
        char name_uninit[100];
        char *name_ptr = NULL;
        char name_default[100] = "anonymous";
    
        if (argc > 1) {
            strcpy(name_uninit, argv[1]); /* beware buffer overflow */
            name_ptr = argv[1];
            strcpy(name_default, argv[1]); /* beware buffer overflow */
        }
    
        /* ... */
    
        /* name_uninit may be unusable (and untestable) if there were no command line parameters */
        /* name_ptr may be NULL, but you can test for NULL */
        /* name_default is a definite name */
    }
    

提交回复
热议问题