1

我在 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。

4

1 回答 1

7

那是您的字符串参数49中的 ASCII 码点。这是因为是一个指针数组,每个指针都指向一个包含参数的 C 字符串。因此,就好像您已定义为.112argvchar 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
于 2012-10-23T05:05:20.327 回答