我正在尝试tom编写一个简单的程序,我接受命令行参数,将其转换为整数并将其打印到屏幕:
int main(…
在
int num = atoi(argv[1]); printf("%s/n", num);
替换格式 "%d\n" ,目前你试着写 NUM 作为一个字符串( %s ),所以 打印 尝试从地址中访问字符的值 NUM 并且该地址无效,导致您的崩溃
"%d\n"
%s
或者当然,假设你的程序至少得到一个参数,那么 ARGC > 1和至少 argv[1] 不是NULL
argv[1]
根据备注的要求,更正和更安全的方法可以是:
#include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { if (argc != 2) fprintf(stderr, "wrong number of argument\nUsage: %s <number>\n", argv[0]); else { int num; char c; if (sscanf(argv[1], "%d%c", &num, &c) == 1) printf("%d\n", num); else fprintf(stderr, "'%s' does not (only) contain an int\n", argv[1]); } return 0; }
编译和执行:
pi@raspberrypi:/tmp $ gcc -pedantic -Wextra i.c pi@raspberrypi:/tmp $ ./a.out wrong number of argument Usage: ./a.out <number> pi@raspberrypi:/tmp $ ./a.out 12 12 pi@raspberrypi:/tmp $ ./a.out a 'a' does not (only) contain an int pi@raspberrypi:/tmp $ ./a.out 12a '12a' does not (only) contain an int
我用 sscanf的 而不是 的atoi 因为 的atoi 如果参数不是有效整数,则返回0而不指示错误。
我让你看 添加两个char数组的值 有关详细信息,包括使用 strtod转换
#include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { if (argc < 2) { printf("You must provide a command-line argument.\n"); return 1; } int num = atoi(argv[1]); printf("%d\n", num); return 0; }
正如其他人所说,除非argc至少为2(表示在运行程序时必须至少提供一个命令行参数),否则不能在没有segfaulting的情况下访问argv [1]。问题可能是您通过不向程序提供命令行参数来取消引用空指针。