gpt4 book ai didi

c - Argc 返回 1,argv 返回 NULL,尽管输入了命令行参数

转载 作者:太空宇宙 更新时间:2023-11-04 07:03:07 30 4
gpt4 key购买 nike

我想我对 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;
}

最佳答案

像许多编程语言一样,在 C 中,argv[0] 通常包含程序的名称。该值实际上取决于用于启动进程的 exec* 系统调用的参数。出于您的目的,该部分无关紧要。需要注意的重要一点是 argc 总是比您的程序在命令行上接收到的参数数量大 1。在你的情况下 argc == 3argv 的值应该看起来像

argv[0]: "./foo"
argv[1]: "-n"
argv[2]: "10"

您的程序出现段错误的原因是您在 optarg 不再有效后访问它。每次调用 getopt() 时,optarg 的值都会改变。当您在 while 循环之外调用它时,它已更改为 NULL。在 'n' 的 switch case 中时,您应该将 atoi(optarg) 的值存储到一个变量中。

由于您仍然对此感到困惑,我已经用必要的修复更新了您的代码。

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;
int n = -1;

while((c = getopt(argc, argv, ":n:")) != -1) {

switch(c) {
case 'n':
n = atoi(optarg);
if(n > 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(n);
}
break;
}
}

if (n == -1)
{
printf("You must specify a value with -n\n");
return 1;
}

printf("The %d Fibonacci term is %lu\n", atoi(optarg), array[n]);

return 0;
}

关于c - Argc 返回 1,argv 返回 NULL,尽管输入了命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35675103/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com