C中的命令行参数 - 传递12,机器读数49

时间:2012-10-23 05:03:13

标签: c command-line-arguments

我在C:

中有这段代码
int x = 52706108;

 if(argc >= 2){
  int val = *argv[1];
  int xor = x^val;
  printf("The xor value between %d and %d is %d in decimal\n",x,val,xor);
 }

我正在编译它:

gcc -m32 -g -o a5_1 a5_1.c

像这样运行:

./a5_1 12

这是我的输出:

The xor value between 52706108 and 49 is 52706061 in decimal

我无法理解为什么我传递参数“12”,但机器正在读取49。

1 个答案:

答案 0 :(得分:7)

49字符串参数112的ASCII代码点。这是因为argvchar 指针的数组,每个都指向包含参数的C字符串。因此,就好像您已将argv[1]定义为{'1', '2', '\0')

如果要将参数转换为整数,使用类似:

的内容
int num = atoi (argv[1]);

或者,最好进行错误检查,并避免在数字超出范围时出现未定义的行为:

char *nextChar;
long num = strtol (argv[1], &nextChar, 10);
if ((nextChar == argv[1]) || (*nextChar != '\0')) {
    // Is either empty or has invalid characters.
    return -1;
}

// String was non-empty and all-numeric.

完整示例:

#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
    long x = 52706108;
    if (argc >= 2) {
        char *nextChar;
        long val = strtol (argv[1], &nextChar, 10);
        if ((nextChar == argv[1]) || (*nextChar != '\0')) {
            printf ("Invalid input '%s'\n", argv[1]);
            return -1;
        }
        long xor = x^val;
        printf("Xor between %ld and %ld is %ld in decimal\n",x,val,xor);
    }
    return 0;
}

该程序的输出(当给出12作为参数时)是:

Xor between 52706108 and 12 is 52706096 in decimal