2

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];
int 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?

Community
  • 1
  • 1
CryptoJones
  • 734
  • 3
  • 11
  • 33
  • 1
    Not the answer, but please initialize `i` before using it. – Jacob Krall Apr 27 '11 at 02:44
  • Hello Aaron. Welcome to Stack Overflow. Thank you very much for including a complete, compilable program in your question. I reformatted your question so that the code would appear correctly. In future, please do that yourself: highlight your code and use the `{}` button to include it in a code block. Once again, welcome. I hope you ask and answer a lot of questions here. – Robᵩ Apr 27 '11 at 02:44
  • @Jacob: since `i` is "global", it's initialized to 0. – Alok Singhal Apr 27 '11 at 03:04

2 Answers2

5

You are comparing words[i] and "help" for pointer equality, not string equality. I think you meant: if (strcmp(words[i], "help") == 0) {

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • 2
    Remember `==` compares everything as if it were an integer. If you throw pointers at it, it will compare them mathematically: two structures can be semantically equal, but if you compare the pointers to them, they'll be different. – salezica Apr 27 '11 at 02:44
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.

Zach Rattner
  • 20,745
  • 9
  • 59
  • 82
  • There are languages in which arrays of characters can be compared with `==`. The problem is that strings and arrays are not first-class objects in C (people who only know C, or only know less primitive languages, are likely to both be baffled by that statement, for opposite reasons), so they are converted to their addresses (a concept that may not make sense to non-C programmers) when used in an expression. Also `strcmp` is normally used for string comparison and is appropriate here. – Jim Balter Apr 27 '11 at 03:01