【发布时间】:2018-07-11 22:09:13
【问题描述】:
我有一个任务。该程序将打印 C 中所有命令行参数的总和。我尝试了它编译的这段代码,但在控制台中传递参数后抛出错误。下面是代码。
/* Printing sum of all command line arguments */
#include <stdio.h>
int main(int argc, char *argv[]) {
int sum = 0, counter;
for (counter = 1; counter <= argc; counter++) {
sum = atoi(sum) + atoi(argv[counter]);
}
printf("Sum of %d command line arguments is: %d\n", argc, sum);
}
编译后会输出Segmentation fault (core dumped) 错误。您的经验可能会解决我的问题。
下面是我编辑的代码:
/* Printing sum of all command line arguments*/
#include <stdio.h>
#include <stdlib.h> // Added this library file
int main (int argc, char *argv[]) {
int sum = 0, counter;
for (counter = 1; counter < argc; counter++) {
// Changed the arithmetic condition
sum = sum + atoi(argv[counter]);
// Removed the atoi from sum variable
}
printf("Sum of %d command line arguments is: %d\n", argc, sum);
}
【问题讨论】:
-
@AnudeepSyamPrasad 教你使用
"stdio.h"和atoi的人不是“最好的”,而是江湖骗子。 -
@Mawg 在 CR 上发布的不正确建议是 meta 上的烫手山芋,例如,请参阅这个新鲜的讨论:meta.stackoverflow.com/questions/362417/…
-
@Lundin 当您的代码工作时,将其发布到我们的姊妹网站 codereview.stackexchange.com。不错的推荐
-
@BjornA。 C11 7.22.1 “如果结果的值无法表示,则行为未定义。”基本上,如果你给它任何不是 ASCII 数字的东西,这个函数肯定会出错。与
strtol系列函数不同,它们具有 100% 等效的功能,但不会出错。 -
@Ian atoi 假设它得到了一个以空字符结尾的字符串,只包含有效数字。如果它得到其他任何东西,它就会出错。使用它没有任何意义,因为
strtol系列函数具有相同 功能(以及更多),以及正确的错误处理。它与多线程无关。
标签: c syntax-error command-line-arguments atoi