2

I have the below part of code in which I noticed that if I change the 0 to 1 the result is the same. I get the STACKprint(); with "on" as the second argument, nothing with anything else and if there is no argument I get a segmentation fault. I guess for the segmentation fault I need to check if the argument is NULL but I am not sure how to do that with the second parameter and it really bugs me out why (strcmp (argv[2],"on") == 1) has no effect. Is it not supposed to take a TRUE value?

 if (strcmp (argv[2],"on") == 0) {
            STACKprint();
            printf("\n");
 }
Jay
  • 9,585
  • 6
  • 49
  • 72
apot
  • 39
  • 1
  • 1
  • 4

3 Answers3

4

To avoid the segfault, check the value of argc to discover whether argv[2] exists. If argc < 3, argv[2] wasn't supplied.

strcmp() doesn't return true/false; it returns a value either less than, equal to, or greater than zero depending on the relative values of its arguments.

3

First of all, to check if there is an argument, you should use the argc variable of the main(int argc, char** argv), which indicates the length of your argv array.

if (argc < 3) {
  printf("missing argument\n");
  exit(-1);
}

As for strcmp, the man page only states that it returns 0 if the two strings in argument are equal, else non-zero... but not necessarily 1. In fact it is implementation dependent. The way to use it to check for string equality is therefore :

if (0 == strcmp(argv[2], "on")) {
   // do something
} else {
   // do something else
}
1

If your program is something like this

#include <stdio.h>


  int main (int argc, char**argv)
  {
     if (argc >= 3 && strcmp (argv[2],"on") == 1){
  //        STACKprint();
          printf("\n");
      }
  }

and you try to run it with myexe 1 on, It will never go into the if block and if you change the 1 to 0, it will go.

Something else is wrong.

It will be nice if you can post your code and the way you are calling it.

Jay
  • 9,585
  • 6
  • 49
  • 72
Ritesh
  • 1,809
  • 1
  • 14
  • 16