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"); } 
4
  • 6
    To prevent the segmentation fault, you need to check argc. Commented Jul 28, 2015 at 16:19
  • 2
    You would use argc (a count) to determine if argv[2] exists. Commented Jul 28, 2015 at 16:20
  • 1
    @aschepler Sorry for stupid question but what is STACKprint() ? Commented Jul 28, 2015 at 16:20
  • 1
    Changing 0 to 1 should change the outcome. Something else is wrong. Could you edit your post to include the entire main() function, with the 1 in place, and show the output, too? Commented Jul 28, 2015 at 16:23

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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 Comment

You mean argc<3, since he's using argv[2], right?
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.

2 Comments

Sure you want strcmp (argv[2],"on") == 1 instead of strcmp (argv[2],"on") == 0 or strcmp (argv[2],"on") != 0?
Good point @chux. This is not going to work as expected (programiz.com/c-programming/library-function/string.h/strcmp0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.