Since you iterate to counter == argc , you point a NULL pointer to atoi() , it's simple, just rely on the fact that the argv array has a NULL watchdog timer and does this
#include <stdlib.h> /* For `atoi()' */ #include <stdio.h> /* For `printf()' */ int main(int argc, char *argv[]) { int sum; sum = 0; for (int counter = 1; argv[counter] != NULL; ++counter) { sum += atoi(argv[counter]); } printf("Sum of %d command line arguments is: %d\n", argc, sum); }
Note that atoi(sum) is undefined because sum is int and is not a valid pointer. Until atoi() tries to dereference it.
Finally, enable stdlib.h for atoi() . I know that you did not enable it because I have warnings for my compiler, and it warned me that atoi() implicitly defined. This may work, but only because the undefined behavior is UNDEFINED.
Also note that there is no way to find out if the passed argument is integer, since atoi() cannot perform error checking. Instead, you can use strtol() and check if all values ββare integers.
So ... here's how you could write a more reliable version of this program
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int sum; sum = 0; for (int counter = 1; argv[counter] != NULL; ++counter) { char *endptr; sum += strtol(argv[counter], &endptr, 10); if (*endptr != '\0') { fprintf(stderr, "error: the `%d-th' argument `%s', is not a valid integer\n", counter, argv[counter]); return EXIT_FAILURE; } } printf("sum of %d command line arguments is: %d\n", argc, sum); return EXIT_SUCCESS; }
EDIT . To address this comment
There is a possibility that argc == 0 , for example, if you execute a program through one of the functions exec*() . In this case, you should check before starting the loop or argv[counter] will be one element after the last, that is, outside.