【发布时间】:2016-06-11 01:10:33
【问题描述】:
我想我对 C 命令行参数有点生疏了。我查看了我的一些旧代码,但不管这个版本是什么,都会出现段错误。
运行方式是 ./foo -n num(其中 num 是用户在命令行中输入的数字)
但不知何故,它不起作用。我哪里错了?
编辑:当我尝试访问 atoi(optarg) 时出现段错误,它是段错误的 atoi(0x0)。
int main(int argc, char *argv[])
{
int c;
int maximum_n = max_n(); /* Stores the maximum value in the sequence a long can hold */
unsigned long *array = NULL;
while((c = getopt(argc, argv, ":n:")) != -1) {
switch(c) {
case 'n':
if(atoi(optarg) > maximum_n) {
printf("n is too large -- overflow will occur\n");
printf("the largest Fibonacci term than can be calculated is %d\n", maximum_n);
exit(EXIT_SUCCESS);
}
else {
array = fib_array(atoi(optarg));
}
break;
}
}
printf("The %d Fibonacci term is %lu\n", atoi(optarg), array[atoi(optarg)]);
return 0;
}
【问题讨论】:
-
argv[0]是您的第一个参数,通常的 shell 将其设置为可执行文件的基本名称,顺便说一句。 -
是的,我明白了。这就是为什么我说 argv[1] 是这里的问题,因为它返回 null 但不应该。它应该是用户输入的任何内容。
-
Tyler,你要明白,如果设置了 argv[0],则 argc 为 1。如果设置了 argv[1],则 argc 必须至少为 2。
-
您的意思可能是:
array[atoi(optarg) - 1]。就目前而言,如果您要求第 n 个元素,您实际上得到的是第 (n+1) 个元素。 -
您没有在任何地方直接访问
argv或argc。为什么你认为它们有问题?段错误到底在哪里?
标签: c segmentation-fault command-line-arguments argv argc