Question

Working on a simple C program I'm stuck with an if test:

int line_number = 0;
if ((line_number >= argv[2]) && (line_number <= argv[4]))

gcc says:

cp.c:25: warning: comparison between pointer and integer
cp.c:25: warning: comparison between pointer and integer

What can I do to properly check the range of lines I want to deal with?

Was it helpful?

Solution

Of course it doesn't work: argv is a pointer to pointer to char.. it's not clear what you want to do but think about that argv[2] is third parameter and argv[4] is fifth one. But they are of char* type (they are strings) so if you want to parse them as integers you should do it using the function atoi:

int value = atoi(argv[2]);

will parse int that was as third parameter and place it into variable, then you can check whatever you want.

OTHER TIPS

You should not be using function atoi. If fact, you should forget it ever existed. It has no practical uses.

While Jack's answer is correct in stating that the argv strings have to be converted to numbers first, using atoi for that purpose (specifically in the situation when the input comes from the "outside world") is a crime against C programming. There are virtually no situations when atoi can be meaningfully used in a program.

The function that you should be using in this case is strtol

char *end;
long long_value = strtol(argv[2], &end, 10);
if (*end != '\0' || errno == ERANGE)
  /* Conversion error happened */;

The exact error checking condition (like whether to require *end == '\0') will actually depend on your intent.

If you want to obtain an int in the end, you should also check the value for int range (or for your application-specific range)

if (long_value < INT_MIN || long_value > INT_MAX)
  /* Out of bounds error */;

int value = long_value;
/* This is your final value */
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top