The argv
array is an array of strings, you cannot usefully cast that to an integer since it will give you the integer variant of the pointer.
What you need to do is use a function like strtol
to convert the string to a number. The following complete program contains a function that will do that for you:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int checkStrLong(char *num, long *pValue) {
// Attempt conversion, base ten, get address of first invalid character.
char *nextCh;
long val = strtol (num, &nextCh, 10);
// Reject empty string, ensure whole string was used.
if ((nextCh == num) || (*nextCh != '\0'))
return 0;
// Pass back value.
*pValue = val;
return 1;
}
int main(int argc, char *argv[]) {
int i;
long val;
int len, maxLen = 0;
for (i = 1; i < argc; i++) {
if ((len = strlen(argv[i])) > maxLen) {
maxLen = len;
}
}
for (i = 1; i < argc; i++) {
if (checkStrLong(argv[i], &val)) {
printf ("%-*s: %ld\n", maxLen, argv[i], val);
} else {
printf ("%-*s: <INVALID>\n", maxLen, argv[i]);
}
}
return 0;
}
The following transcript shows it in action for a few test values:
pax> ./testprog 1 -7 42 314159 44.2 21guns hello one23 ""
1 : 1
-7 : -7
42 : 42
314159: 314159
44.2 : <INVALID>
21guns: <INVALID>
hello : <INVALID>
one23 : <INVALID>
: <INVALID>