[LCP]Char Comparisons?

ianezz at kinsale.sodalia.it ianezz at kinsale.sodalia.it
Thu Aug 29 18:16:05 UTC 2002


Una cavalletta salita sulla tastiera di James Mclean ha scritto:

 > 	if(buf=="load") {
 > 	    load();
 > 	} else {
 > 	    usage();
 > 	}


if(strcmp(buf,"load") == 0)
{
    load();
}
else
{
    usage();
}

The problem is that buf, in that context, is basically a ``char *'',
and the string constant "load" is a ``const char *'' (in an
expression, the C compiler just replaces a string constant with the
memory address it is stored at).

So, the ``=='' operator in C simply compares if the two pointers point
to the same memory area (basically, it compares two addresses), while
it disregards completely what they point to. 

Btw, the two pointers can't be equal, since ``buf'' is an array
allocated on the stack (so buf points inside the stack) and string
constants are stored in a completely different memory area.

What you want to do is "compare the string pointed by ``buf'' with the
string constant "load": to do this you have to use the strcmp()
function, which is part of the standard C library.

-- 
 |   \    \  | ___|_  |_  | ianezz AT sodalia.it
 |  _ \  | \ | _|    /   /  Visita il LinuxTrent a
_|_/  _\_|  _|____|___|___| http://www.linuxtrent.it




More information about the linuxCprogramming mailing list