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

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

Is this code correct?

char *argv[] = { \"foo\", \"bar\", NULL };
3条回答
  •  孤城傲影
    2021-01-12 04:29

    It's syntactically correct, and it does create a NULL-terminated array of strings.

    argv is passed to main as char*[] (or equivalently, char**), but it's "more correct" to treat string literals as a const char* rather than a char*. So with this particular example you'd want const char *argv[] = {"foo", "bar", NULL };

    Maybe you aren't really going to initialise it with "foo", but actually with a modifiable string that you will want to modify via argv. In that case char*[] is right. This is the kind of thing Charles probably means by saying that whether code is "correct" depends on what you do with it.

提交回复
热议问题