使用指针,通过迭代的argv [] [英] Using pointers to iterate through argv[]

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

问题描述

我想用下面的code,但没有索引数组[] [],并与指针代替它。

 的for(int i = 0; I< ARGC,我++){
    对于(INT J = 0;的argv [I] [J] ='\\ 0';!J ++){
        // code
    }
}

我知道,你可以使用指针来遍历数组,但我不确定该怎么做,与第二阵列中的一个未定义的长度,在这种情况下,从输入字符串。自的argv的每个元素[]可以具有不同的长度,我想确保我可以正确读取字符和知道的argv []端部的每一个元素,下一个开始时

我希望它是这样的:(如果下面的头主要是不对的,请告诉我。)

  INT主(INT ARGC,字符** argv的){
    的for(int i = 0; I< ARGC,我++){
        而(argv的!='\\ 0'){
            // code
            * argv的+ 1;
        }
        //跳过空字符
        ARGV + 1;
    }
}


解决方案

由于循环允许任何类型的数据,为你的循环索引,不必为整数的循环可以被改写这样的:

 为(字符** A =的argv;!A =的argv + ARGC; A ++){
    对于(的char * p = *一* P ='\\ 0'; P!++){
        // code使用* P代替的argv [I] [J]。
    }
}

内环使用 P 作为循环变量,这是增加与常规点++ ,并检查 * p!='\\ 0'。循环条件可以缩短到 * P ,所以内循环是这样的:

 为(的char * p = *一个; * P,P ++)

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
    }
}

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.

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;
    }
}

解决方案

Since for loop allows any kind of values, not necessarily integers for your "loop index", your loop could be rewritten like this:

for (char **a = argv ; a != argv+argc ; a++) {
    for(char *p = *a ; *p != '\0' ; p++) {
        // code uses *p instead of argv[i][j]
    }
}

The inner loop uses p as the loop variable, which is incremented with the regular p++, and checked with *p != '\0'. The loop condition could be shortened to *p, so the inner loop would look like this:

for(char *p = *a ; *p ; p++)

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

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