Why are my Char * values not equal, if I'm giving them the same value?

These two values are set to the exact same thing basically, but for some reason, crate != "0 HEAD".

1
2
3
4
5
  char crate[7] = "0 HEAD";

	if (crate == "0 HEAD")
		cout << "It Works!"; // This if statement will fail
	cout << endl;


I've tried using consts

My crate[] has an equal capacity to "0 HEAD"

What is wrong?

Thanks!
The solution: Use strings:

1
2
3
4
5
6
7
#include <string>

//...
string crate = "0 HEAD";

if(crate == "0 HEAD")
    cout << "Now this will work";


Strings are all around safer and less error prone than char arrays.


As for the reason why this doesn't work with char arrays -- the language does not support comparison of arrays. So when you do a == comparison with a char array, it's actually comparing pointers and not the contents of the actual string data. So you are comparing a pointer to your 'crate' array, so a pointer to where the "0 HEAD" string exists inside the executable. Those pointers are going to be different, which is why it fails.



EDIT:

If, for whatever reason, you don't want to use strings, you can use strcmp:

1
2
3
4
5
6
7
#include <cstring>

//...
char crate[] = "...";

if( strcmp(crate,"...") == 0 )
    cout << "The strings match";



But really... just use strings.
Last edited on
To add to what Disch said above, the C language added types char (for a byte), int (for a machine word), short int (for a smaller integral type), long int (for a longer integral type), and float and double (for possible hardware supported floating point types) to its predecessor, a language called B. long long and long double were added to a later revision of the language to offer better support to more capable hardware.

Note there are no strings! These were hacked in with arrays of chars. So when you write:
 
   char str["hello"];
The C language reserves 6 bytes and fills them with 'h', 'e', 'l', 'l', 'o', '\0'. The C runtime library has a whole bunch of functions that support this zero terminated (ASCIIZ) string; strcat, strcpy, strcmp, the %s in printf, and so on.

C++ inherited this stuff from C. But you really should use the standard string class. It avoid all the problems such as the you've run into.
Last edited on
OK. That was super helpful. Thanks guys!
Topic archived. No new replies allowed.