I'm calling a simple executable as follows:
$ ./test -l 123
I have some relatively simple code that checks whether there are enough args provided, and if not prompts the user to enter the value instead.
The code looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
int main(int argc, char *argv[])
{
long max_number;
char out[1024];
// Check whether max_number was passed via args
if (argc < 2) {
printf("Enter the maximum number: ");
fflush(stdout);
scanf("%d", &max_number);
} else {
for (int i=1; i<argc; i++) {
sprintf(out, "%sArg %d of %d is '%s'\n", out, i, argc, argv[i]);
if (strcmp(argv[i], "-l") && argc > i) {
sprintf(out, "%sFound '-l' argument at index %d\n", out, i);
int argTarget = i + 1;
sprintf(out, "%sLooking for the maximum number at argument %d\n", out, argTarget);
max_number = atoi(argv[argTarget]);
}
}
}
printf("%s", out);
printf("Maximum number received: %d\n", max_number);
return 0;
}
What I would expect to come from the command above is:
Arg 1 of 3 is '-l'
Arg 2 of 3 is '123'
Found '-l' argument at index 1
Looking for the maximum number at argument 2
Maximum number received: 123
What actually happens is this:
Arg 1 of 3 is '-l'
Arg 2 of 3 is '123'
Found '-l' argument at index 2
Looking for the maximum number at argument 3
Maximum number received: 0
So for some reason, despite the fact that I can get the value from index i
no problem, when I try to get the value of i
it seems to be one higher than it's supposed to be. I don't understand why it's correct when I check it on the first line of the for
loop, but when I check it after the strcomp()
it seems to be incorrect.
Can anyone help me understand what's going on here?
I'm using GCC on Windows 10 and running in a MinGW-64 terminal. To compile I'm simply running:
$ gcc args.c -o args