正确的方法来初始化字符串在C NULL结尾数组 [英] Correct way to initialize a NULL-terminated array of strings in C
问题描述
这是code正确吗?
的char * argv的[] = {富,酒吧,NULL};
这是语法正确的,它也创造字符串的NULL结尾数组。
ARGV传递给主
为的char * []
(或等价,字符**
),但它的更正确对待字符串作为为const char *
而非的char *
。因此,与这个特殊的例子中,你会想要为const char * argv的[] = {富,酒吧,NULL};
也许你是不是真的有富初始化,但实际上,你将要通过的argv修改修改字符串。在这种情况下,的char * []
是正确的。这是什么样的事情查尔斯可能是说,code是正确的取决于你用它做什么意思。
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.
这篇关于正确的方法来初始化字符串在C NULL结尾数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!