PDA

View Full Version : simple question on pointer-arrays



mickey
16th February 2007, 21:30
hi, I coded this:


int main (int argc, char* argv[]) {
cout << argv[1] << endl;
if (argv[1] == "hi") cerr << " hello\n";
char* p = "hi";
if (p == "hi") cout << "hello\n";

at console I need to launch program so: program.exe hi
and I don't understand why cout prints 'hi' but the first if isn't executed. isn't argv an array of char* ??? then why then second if is executed???
thanks

jacek
16th February 2007, 21:56
You are comparing pointers not strings. Either compare strings using strcmp() or use std::string instead of char *.

Methedrine
17th February 2007, 02:11
You are comparing pointers not strings. Either compare strings using strcmp() or use std::string instead of char *.

Exactly. argv is char**, so the = operator will compare the memory address of your "hi" with the memory address of argv[1]. And it would be a shitload of (bad) luck if these two addresses are the same ;)