从 C 中的命令行参数打印整数

Printing integers from command line arguments in C

我是 运行 我的程序,带有一些命令行参数。但是当我输入 10、10、10 并将它们打印出来时,它会打印出 49、49、49。这是我的代码:

int main(int argc, char *argv[]) {
    int seed = *argv[0];
    int arraySize = *argv[1];
    int maxSize = *argv[2];

为什么会这样??

嗯,argv 是一个指向字符串的指针数组。所有命令行参数都作为 strings 传递,并且指向每个参数的指针由 argv[n] 保存,其中参数的序列为 n+1.

对于托管环境,引用 C11,章节 §5.1.2.2.1

If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment. If the value of argc is greater than one, the strings pointed to by argv[1] through argv[argc-1] represent the program parameters.

所以,很明显,对于像

这样的执行

./123 10 10 10 //123 is the binary name

  • argv[0]不是第一个"command line argument passed to the program"。这是 argv[1].
  • *argv[1] 不会 return 您作为命令行参数传递的 int 值。

    基本上,*argv[1] 为您提供 字符串 的第一个元素的值(即 '1'char 值) ,最有可能是 ASCII 编码值(您的平台使用),根据 ascii table a '1' 的 ansd 具有您看到的 49 的十进制 va;lue。

解决方案:您需要

  • 检查参数数量 (argc)
  • 遍历每个参数字符串 argv[1] ~ argv[n-1]argc == n
  • 将每个输入 string 转换为 int(对于这种情况,您可以使用 strtol()

解引用一个字符串 (*argv[x]) 得到一个 char(字符串中第一个字符的值),在这种情况下,该值是 ASCII '1':十进制 49

您可以使用 strtol

转换这些字符串(无需取消引用)
int arraySize = (int)strtol(argv[1], NULL, 10);

反正argv[0]是你的程序名,你确定程序名是以1开头的吗?