我在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。
答案 0 :(得分:7)
49
是字符串参数1
中12
的ASCII代码点。这是因为argv
是char
指针的数组,每个都指向包含参数的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