c - Basic Bool function giving segmentation fault -
so i'm trying learn functions bit better , able write 1 useful , in 1 recursive , sorts list of number given program. i'm getting segmentation fault here. feel occuring when try read argv[i+1]
when have run out of entries in argv[]
. why doesn't if(i < argc){
statement checking preclude happening?
here's code.
#include <stdio.h> #include <ctype.h> #include <math.h> #include <string.h> #include <stdbool.h> bool compare(val1,val2) { if(val1 > val2){return false;} else{return true;} } // int values[], int n int main(int argc, char *argv[]) { for(int i=1; i<argc; i++){ //print unsorted list printf("%s\n",argv[i]); if(i < argc){ if(compare(*argv[i],*argv[i+1])) { printf("true\n"); } else { printf("false\n"); } } // add else odd numbered lists } return 0; }
argv[i+1]
not defined if i==argc-1
.
for example, if argc=3
means using 2 arguments (argv[0]
, argv[1]
, , argv[2]
defined). trying access argv[3]
when call argv[i+1]
when i
equal 2
.
all have redefine for
, remove if(i < argc)
.
your code may this:
for(int i=1; < argc-1; i++){ //print unsorted list printf("%s\n",argv[i]); if(compare(*argv[i],*argv[i+1])) printf("true\n"); else printf("false\n"); }
Comments
Post a Comment