Is this code correct?
char *argv[] = { \"foo\", \"bar\", NULL };
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.
There's nothing obviously wrong the declaration or the initialization but whether it is "correct" depends on what the rest of the code actually does with argv
.
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).