Pretty straightforward, I am trying to sum all of the integers input in the command line. The sum actually works, if I start the program with " 1 1 1 1 " input, the sum increments by one four times. The problem is that sum is initialized at some really large number (4293283588). Why is that?
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]
is perhaps the name of the executable. From the standard:
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 .
Try
for (i=1; i<argc; i++)
Also, as @BLUEPIXY indicated, %ld
assumes type long
. So either change it to %d
, or use long sum
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.