Why doesn't this return true?
Apr 18, 2012 at 10:44pm Apr 18, 2012 at 10:44pm UTC
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
using namespace std;
int main()
{
char word1[]="hello" ,word2[]="hello"
if (word1==word2)
cout<<"word1 equals word2" ;
else
cout<<"word1 does not equal word2" ;
}
The output is "word1 does not equal word2". Is this because the if statement is checking to see if the addresses of the arrays are equal, and not the actual content of the arrays?
Apr 18, 2012 at 10:53pm Apr 18, 2012 at 10:53pm UTC
Yes, the value of word1 and word2 are memory addresses. Try this instead:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char word1[] = "hello" ;
char word2[] = "hello" ;
if (!strcmp(word1, word2))
cout << "word1 equals word2" ;
else
cout << "word1 does not equal word2" ;
return 0;
}
strcmp returns 0 if two cstrings are equal.
Last edited on Apr 18, 2012 at 10:55pm Apr 18, 2012 at 10:55pm UTC
Apr 18, 2012 at 10:56pm Apr 18, 2012 at 10:56pm UTC
Okay, thanks for clearing that up.
Topic archived. No new replies allowed.