0

I'm debugging my C++ code on Ubuntu which I execute as ./main path < input.txt

argv[1] should contain a string "path" which verified by GDB below.

However, the program always jumps over my first condition even though argv[1] == "path" should return true.

Any idea?

...
(gdb) n
181     if(argv[1] == "path")
(gdb) p argv[1]
$1 = 0xbffffba3 "path"
(gdb) n
183     else if(argc == 1)
(gdb) 
Avery
  • 2,270
  • 4
  • 33
  • 35
user3081703
  • 63
  • 1
  • 8
  • possible duplicate of [How do I properly compare strings in C?](http://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c). Although this question was in C++, the question I linked to applies to both C and C++. – Dennis Meng Mar 05 '14 at 05:34

1 Answers1

2

Even though the two strings are the same, they occupy a different location in memory. When it is checking whether argv[1] is equal to a fixed-string "path", it is not doing it character-by-character: it is looking to see whether the pointer to the fixed-string "path" is the same as the argv[1] variable passed into main(), which it is not.

You need to use strcmp to test the equality of those two strings:

if (strcmp(argv[1], "path") == 0) { /* they match */ }
OnlineCop
  • 4,019
  • 23
  • 35
  • Doesn't C++ overload `==` for string comparisons though? – Dennis Meng Mar 05 '14 at 05:30
  • If only! Sadly, C++ tries to keep as much compatibility with original C as possible, and since `==` in C would check the pointers against each other, C++ does not want to break this style. You might be able to overload it yourself, and maybe `std::string` has some better operations, but remember that neither `argv[1]` nor `"path"` are type `std::string`: they are a `char*` or `const char*` array, respectively. – OnlineCop Mar 05 '14 at 05:33