c - Segmentation fault in program using command line arguments -
i'm trying write program finds largest , smallest of 10 numbers.
to use program, must use command line argument -l numbers determine largest number, same command -s smallest numbers.
however, when don't enter command @ all, , try run program, receive segmentation fault. not sure went wrong.
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* argv[]) { int i; int min,max,num; char *argv1 = argv[1]; char *small = "-s"; char *large = "-l"; min=max=0; if (0==strcmp(argv1, small)) { (i=2; i<argc; i++) { num=atoi(argv[i]); if(i==2) { min=num; } else { if(min>num)min=num; } } printf("the smallest number %d\n",min); } else if (0==strcmp(argv1, large)) { (i=2; i<argc; i++) { num=atoi(argv[i]); if(i==2) { max=num; } else { if(max<num)max=num; } } printf("the largest number %d\n",max); } else { printf("invalid option"); } return 0; }
check number of arguments before accessing arguments.
int main(int argc, char* argv[]) { int i; int min,max,num; char *argv1 = argv[1]; char *small = "-s"; char *large = "-l"; /* add here */ if(argc < 2) { fprintf(stderr, "usage: %s command numbers...\n", argc > 0 ? argv[0] : ""); return 1; } /* add until here */ min=max=0;
Comments
Post a Comment