C String Comparison Failure? [duplicate]
Possible Duplicate:
C String — Using Equality Operator == for comparing two strings for equality
I have the following code;
#include <stdio.h>
#define MAXLINE 2600
char words[4][MAXLINE];
i开发者_如何学运维nt i;
int main(){
printf("Enter menu option: ");
scanf("%s", words[i]);
printf ("\n %s was entered!", words[i]);
if (words[i]=="help"){
printf("\nHelp was requested");
}
else
{
printf("\nCommand not recognized!");
}
}
The array evaluation in the if statement isn't working. I am obviously doing something wrong. Can someone explain to me what?
You are comparing words[i]
and "help"
for pointer equality, not string equality. I think you meant: if (strcmp(words[i], "help") == 0) {
In C, strings (sequences of characters) are treated as arrays of characters. As a result, you shouldn't compare arrays using the ==
operator.
The array braces []
are just syntactic sugar to hide the pointer arithmetic that's going on under the hood. In general, arr[i]
is identical to *(arr + i)
. Using this information, let's take a look at your comparison:
words[i]
-> *(words + i)
, which is a pointer to an array of characters.
If you want to compare strings, use strncmp.
精彩评论