主 null 中的 char * argv[] 参数是否终止? [英] Are char * argv[] arguments in main null terminated?

查看:23
本文介绍了主 null 中的 char * argv[] 参数是否终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想知道命令行参数是否总是以空字符结尾?谷歌似乎说是的,在 GCC 上编译表明情况确实如此,但我能保证这总是正确的吗?

So I'm wondering if command line parameters are always null terminated? Google seems to say yes, and compiling on GCC indicates this is the case, but can I guarantee this to always be true?

int main(int argc, char** argv)
{
    char *p;

    for(int cnt=1; cnt < argc; ++cnt)
    {
        p = argv[cnt];
        printf("%d = [%s]\n", cnt, p);
    }
    return 0;
}

$ MyProgram -arg1 -arg2 -arg3
1 = -arg1
2 = -arg2
3 = -arg3

推荐答案

是的.argv 数组中的非空指针指向 C 字符串,根据定义,它们以空字符结尾.

Yes. The non-null pointers in the argv array point to C strings, which are by definition null terminated.

C 语言标准只是声明数组成员应包含指向字符串的指针"(C99 §5.1.2.2.1/2).字符串是由第一个空字符终止并包括第一个空字符的连续字符序列"(C99 §7.1.1/1),也就是说,根据定义,它们是空终止的.

The C Language Standard simply states that the array members "shall contain pointers to strings" (C99 §5.1.2.2.1/2). A string is "a contiguous sequence of characters terminated by and including the first null character" (C99 §7.1.1/1), that is, they are null terminated by definition.

此外,argv[argc] 处的数组元素是一个空指针,因此数组本身在某种意义上也是空终止".

Further, the array element at argv[argc] is a null pointer, so the array itself is also, in a sense, "null terminated."

这篇关于主 null 中的 char * argv[] 参数是否终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆