使用指针遍历 argv[] [英] Using pointers to iterate through argv[]

查看:20
本文介绍了使用指针遍历 argv[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用以下代码,但不使用[][]"索引数组并用指针替换它

I want to use the following code, but without indexing the array with"[][]" and substitute it with pointers

for (int i = 0; i < argc; i++) {
    for (int j = 0; argv[i][j] != '\0'; j++) {
        //code
    }
}

我知道你可以使用指针来遍历一个数组,但我不确定如何在第二个数组中使用未定义的长度来做到这一点,在这种情况下是来自输入的字符串.由于 argv[] 的每个元素可以有不同的长度,我想确保我可以正确读取字符并知道 argv[] 的每个元素何时结束,下一个开始.

I know that you can use pointers to traverse an array, but I'm unsure how to do that with an undefined length in the second array, in this case the string from input. Since each element of argv[] can have a different length, I want to make sure that I can properly read the characters and know when each element of argv[] ends, and the next begins.

我希望它是这样的:(如果 main 的以下标头是错误的,请告诉我.)

I expect it to be something like: (If the following header to main is wrong, please tell me.)

int main(int argc, char **argv) {
    for (int i = 0; i < argc; i++) {
        while(argv != '\0') {
            //code
            *argv+1;
        }
        //to skip null character
        argv+1;
    }
}

推荐答案

鉴于 argv 中的最后一个元素是 NULL,您不需要对其进行索引或如果你真的不想,就用 argc 比较任何东西.

Given that the last element in argv is NULL, you don't need to index it or compare anything with argc if you really don't want to.

int main(int argc, char *argv[]) {
  for (char **arg = argv; *arg; ++arg) { // for each arg
    for (char *p = *arg; *p; ++p) {      // for each character
      process(*p);
    }
  }
}

*arg 将是 NULL 在参数列表的末尾,这是假的.*p 将在每个字符串的末尾为 '\0',这是错误的.

*arg will be NULL at the end of the list of arguments, which is false. *p will be '\0' at the end of each string, which is false.

来自 N1256 5.1.2.2.1/2

From N1256 5.1.2.2.1/2

如果声明了它们,则主函数的参数应遵守以下约束:

If they are declared, the parameters to the main function shall obey the following constraints:

——argc 的值必须是非负的.

— The value of argc shall be nonnegative.

——argv[argc] 应为空指针.

— argv[argc] shall be a null pointer.

这篇关于使用指针遍历 argv[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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