Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing command parameter with argv[] is not working

Tags:

c++

c

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.

like image 488
itsaboutcode Avatar asked Jul 29 '10 17:07

itsaboutcode


People also ask

What is the data type for argv in command line argument?

argv is an array of pointers to characters.

Is it char * argv or char * argv?

char** argv is the same as char* argv[] because in the second case "the name of the array is a pointer to the first element in the array".

What is the difference between argc and argv?

The first parameter, argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. The second parameter, argv (argument vector), is an array of pointers to arrays of character objects.

Can argv be a string?

The second argument to main, usually called argv, is an array of strings. A string is just an array of characters, so argv is an array of arrays. There are standard C functions that manipulate strings, so it's not too important to understand the details of argv, as long as you see a few examples of using it.


2 Answers

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.

like image 70
Adrian Avatar answered Oct 05 '22 04:10

Adrian


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

}
like image 35
Mark B Avatar answered Oct 05 '22 06:10

Mark B