C语言 将 argv[1] 存储到 char 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21136735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
store argv[1] to an char variable
提问by yaylitzis
I pass a character to my program and I want to store this character to variable. For example I run my program like this ./a.out s file. Now I want to save the argv[1] (its the s) to a variable (lets say I define it like this char ch;. I saw this approach:
我将一个字符传递给我的程序,我想将此字符存储到变量中。例如,我像这样运行我的程序./a.out s file。现在我想将 argv[1] (它的 s)保存到一个变量中(假设我像这样定义它char ch;。我看到了这种方法:
ch = argv[1][0];
and it works. But I cant understand it. The array argv isnt a one dimensional array? if i remove the [0], I get a warning warning: assignment makes integer from pointer without a cast
它有效。但我无法理解。数组 argv 不是一维数组?如果我删除 [0],我会收到警告warning: assignment makes integer from pointer without a cast
回答by trojanfoe
If you look at the declaration of main()you see that it's
如果你看一下你的声明,main()你会发现它是
int main(int argc, const char **argv);
or
或者
int main(int argc, const char *argv[]);
So argvis an array of const char *(i.e. character pointers or "C strings"). If you dereference argv[1]you'll get:
所以argv是阵列const char *(即,字符指针或“C串”)。如果您取消引用,argv[1]您将得到:
"s"
or:
或者:
{ 's' , ''s'
' }
and if you dereference argv[1][0], you'll get:
如果你取消引用argv[1][0],你会得到:
const char *myarg = NULL;
int main(int argc, const char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: myprog myarg\n");
return 1;
} else if (strlen(argv[1]) != 1) {
fprintf(stderr, "Invalid argument '%s'\n", argv[1]);
return 2;
}
myarg = argv[1];
// Use argument as myarg[0] from now on
}
As a side note, there is no need to copy that character from argv[1], you could simply do:
作为旁注,无需从 复制该字符argv[1],您可以简单地执行以下操作:
char* argv[]
回答by Yu Hao
argvis an array of strings, or say, an array of char *. So the type of argv[1]is char *, and the type of argv[1][0]is char.
argv是一个字符串数组,或者说,一个char *. 所以类型argv[1]是char *,类型argv[1][0]是char。
回答by David Heffernan
The typical declaration for argvis
的典型声明argv是
int main(int argc, char *argv[])
That is an array of char*. Now char*itself is, here, a pointer to a null-terminated array of char.
那是一个char*. 现在char*它本身就是一个指向空终止数组的指针char。
So, argv[1]is of type char*, which is an array. So you need another application of the []operator to get an element of that array, of type char.
所以,argv[1]是类型char*,它是一个数组。因此,您需要使用[]运算符的另一个应用程序来获取该数组的元素,类型为char。
回答by Juan Ramirez
Lets see mains' signature:
让我们看看电源的签名:
##代码##No, argvis not a one-dimensional array. Its is a two-dimensional char array.
不,argv不是一维数组。它是一个二维字符数组。
argv[1]returns char*argv[1][0]returns the first char in inargv[1]
argv[1]返回字符*argv[1][0]返回 in 中的第一个字符argv[1]

