11

I am trying to compare the parameter of command with argv[] but it's not working. Here is my code.

./a.out -d 1

In main function

int main (int argc, char * const argv[]) {

if (argv[1] == "-d")

    // call some function here

}

But this is not working... I don't know why this comparison is not working.

philant
  • 34,748
  • 11
  • 69
  • 112
itsaboutcode
  • 24,525
  • 45
  • 110
  • 156

4 Answers4

31

You can't compare strings using ==. Instead, use strcmp.

#include <string.h>

int main (int argc, char * const argv[]) {

if (strcmp(argv[1], "-d") == 0)

// call some function here

}

The reason for this is that the value of "..." is a pointer representing the location of the first character in the string, with the rest of the characters after it. When you specify "-d" in your code, it makes a whole new string in memory. Since the location of the new string and argv[1] aren't the same, == will return 0.

Adrian
  • 14,931
  • 9
  • 45
  • 70
14

In C++ let std::string do the work for you:

#include <string>
int main (int argc, char * const argv[]) {

if (argv[1] == std::string("-d"))

// call some function here

}

In C you'll have to use strcmp:

if (strcmp(argv[1], "-d") == 0)

// call some function here

}
Mark B
  • 95,107
  • 10
  • 109
  • 188
2

You may want to use strcmp here.

Brandon Horsley
  • 7,956
  • 1
  • 29
  • 28
-4

won't that be:

if (argv[0] == "-d")

0 not 1?

chown
  • 51,908
  • 16
  • 134
  • 170
Viper_Sb
  • 1,809
  • 14
  • 18