2

如何将命令行 arg 复制到中的变量c?如果要执行以下操作。

myprog "Hello, world!"

我想将参数的值存储在char变量中。不确定我是否朝着正确的方向前进。

假设始终只传入 1 个参数。

int main (int argc, char  *argv[]){

  int len;
  len=strlen(argv[1]);
  char *array;

  array= malloc((len +1) * sizeof(char));
  int i;
  for(i=0;i<=len;i++){

    // This does not work... am a little lost
    array[i]=*(argv+1)[i];

  }
...
}

有人可以指出我正确的方向。

4

2 回答 2

7

如果您不打算操纵参数,则可以复制指针,如下所示:

int main(int argc, char* argv[]) {
    char* array;

    array = argv[1];

    ...
}

否则,您可以像这样复制字符串:

int main(int argc, char* argv[]) {
    char* array;

    array = strdup(argv[1]);
}
于 2013-09-28T01:54:01.803 回答
1

看起来像运算符优先级问题。代码*(argv+1)[i]被评估为*((argv+1)[i])你想要的是什么(*(argv+1))[i]。你最好只使用argv[i][0].

评估 as*((argv+1)[i])等价于*(*((argv+1)+i))which is *(*(argv+1+i))which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is which is that””””””“评估 as”(也称为“as”)”等价于“评估”(“as”),*(argv[i+1])它试图从 len+1 中挑选出参数 #1 的第一个字符。

一般来说,如果您使用下标而不是指针算术,您的代码会更清晰。不必要的指针算术最好留给求职面试中的难题。

于 2013-09-28T02:03:54.390 回答