非常简单,我正在尝试对命令行中输入的所有整数求和。总和实际上有效,如果我以“1 1 1 1 ”输入启动程序,总和将增加四次。问题是 sum 被初始化为某个非常大的数字 (4293283588)。这是为什么?
int main(int argc, char*argv[])
{
int a = 0;
int sum = 0;
size_t i = 0;
for (i=0; i<argc; i++)
{
a = atoi(argv[i]);
sum = sum + a;
printf("%ld\n", sum);
}
return 0;
}
最佳答案
argv[0]
可能是可执行文件的名称。来自标准:
5.1.2.2.1 Program startup
....
If the value of
argc
is greater than zero, the string pointed to byargv[0]
represents the program name;argv[0][0]
shall be the null character if the program name is not available from the host environment. If the value ofargc
is greater than one, the strings pointed to byargv[1]
throughargv[argc-1]
represent the program parameters.
尝试
for (i=1; i<argc; i++)
此外,正如 @BLUEPIXY 指出的那样,%ld
假定类型为 long
。因此,要么将其更改为 %d
,要么使用 long sum
。
关于c - 总结命令行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26090997/