简体   繁体   English

命令行参数中出现字母

[英]Occurrence of alphabets in a command line argument

I'm having some difficulty with the argv pointer. 我在使用argv指针时遇到了一些困难。 Using *argv[1] gives me the argc count and *argv[2] the entire argument. 使用* argv [1]可以给我argc计数,* argv [2]可以给我整个参数。 Shouldn't each element, when dereferenced give one character? 取消引用时,每个元素都不应该给出一个字符吗?

Thanks 谢谢

int main(int argc,char *argv[])
{
    char store[10]={0,0,0,0,0,0,0,0,0,0};int freq[10]={0,0,0,0,0,0,0,0,0,0};int flag=0;int count=0;int t;
    for(int i=0,j=0;i<argc;i++)
    {
        for(int z=0;z<count;z++)
        {   
        if(i==0) break;
            if(*argv[i+2]==store[z]) flag=1;t=z;break;
        }
           if(flag==0||i==0) {store[j]=*argv[i+2];j++; count++;}
           else freq[t]+=1;
           flag=0;
    }
    for(int x=0;x<count;x++) cout<<store[x]<<"\t"<<freq[x]<<endl;
}

You getting the segfault at *argv[i+2] when i reaches argc-2 because then you would access the argument string argv[argc] which is not defined. i到达argc-2时,您在*argv[i+2]遇到了段错误,因为那样您将访问未定义的参数字符串argv[argc]

If you want to iterate through the characters of an argument, you should use a two-dimensional access, eg: 如果要遍历参数的字符,则应使用二维访问,例如:

// assume there are two arguments present (argc == 3)
int len = 5; // assume there a 5 chars in argv[2]
for(int k = 0; k < len; k++) {
  // do something for each char
  if(argv[2][k] == 'x') { ... }
}

EDIT: changed example to argv[2] holding the string. 编辑:将示例更改为argv[2]保存字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM