>How does it really work?
When used in an expression, the name of an array is treated as a pointer to the first item in the array. A string literal is really a pointer to char. What does the following print?
Code:
#include <stdio.h>
int main ( void )
{
char a[] = "Test";
printf ( "%p\n", (void *)a );
printf ( "%p\n", (void *)"Test" );
return 0;
}
Not two equal addresses if that's what you were going to say. The chances of that are slim and none, and I'd lean more toward none if I were a betting girl.
Anyway, using the above knowledge, what will the following print (feel free to ignore the warning about logical comparison with a string literal if you get one):
Code:
#include <stdio.h>
int main ( void )
{
char a[] = "Test";
if ( a == "Test" )
printf ( "Equal?!\n" );
return 0;
}
What you would expect is that the contents of a is compared lexographically with the contents of "Test". Of course, if you hang around C programmers, this tendency goes away with time. What really happens is that two addresses that are highly unlikely to be the same are compared.
Now, since we C programmers are kewler () than everyone else, we use a sneaky method of weeding out the pretenders by making string comparison illogical unless you already know C or something similar:
Code:
#include <stdio.h>
#include <string.h>
int main ( void )
{
char a[] = "Test";
if ( strcmp ( a, "Test" ) == 0 )
printf ( "Equal!\n" );
return 0;
}