This C program I am making reads a set of chars from the command line and stores them using an array (argv[]) like so
main (int argc, char *argv[]) {
int temp;
/*prevents no arguments*/
if (argc==1){
printf("Usage;\t[0 < integers < 9] [operators]\n");
exit(0);
}
int i;
for (i = 0 ; i<argc; i++){
temp = argv[i] - '0';
printf("this is char %d ; %d\n",i, temp);
}
}
But all I get after running it in the command line like so;
program 2 4 1 - +
is random garbage
this is char 0 ; -4195956
this is char 1 ; -4195950
this is char 2 ; -4195948
this is char 3 ; -4195946
this is char 4 ; -4195944
this is char 5 ; -4195942
Is there something wrong with the way I’m casting temp? Or am I just getting the idea of pointers (in *argv[]) wrong?
argvis an array of pointers to char. Soargv[X]is a pointer to char (for suitable X). Soargv[X] - some_integral_valueis pointer arithmetic, and returns a pointer (if that subtraction is defined).To access the first element, you need
argv[X][0].Please note that
argv[0]is not the first argument but (usually) the program name. Arguments start atargv[1].