Correct way to initialize a NULL-terminated array of strings in C

前端 未结 3 1094
醉话见心
醉话见心 2021-01-12 04:05

Is this code correct?

char *argv[] = { \"foo\", \"bar\", NULL };
3条回答
  •  攒了一身酷
    2021-01-12 04:41

    Yes, your code is formally correct (see Steve's remark about const though). It will produce an array that is terminated with a null pointer of type char *.

    You can also do

    char *argv[4] = { "foo", "bar" }; 
    

    or

    char *argv[10] = { "foo", "bar" }; 
    

    if your array for some reason has to have a specific size. In this case the extra elements will also be set to null pointers, even though you are not initializing them explicitly. But I'd say that even in this case it is better to use

    char *argv[4] = { "foo", "bar", NULL }; 
    

    because that will make sure that the array is indeed long enough to get null-terminated (if the array happens to be too short, the compiler will generate a diagnostic message).

提交回复
热议问题