0

Possible Duplicate:
How to compare strings in an “if” statement?

I'm using C. My two strings, when compared with the equals == operator, are not matching up, even if the std output looks the same.

Consider one of the arrays started as an array of integers, which I converted to characters by adding a '0' to each integer and loading into another char * array.

So now both arrays are character arrays with characters and the same std output, but my "if" selection structure is not working to match them. I am using the char * name to reference each array.

I could post this entire code if necessary. Here is a loop with the comparison:

i=0;
pipx = (char*)malloc(sizeof(char));
sec = (char*)malloc(sizeof(char));

//for (b = 0; b < lengthx; b++){
    //reallocate a second array
    pipx = (char*)realloc(sec, ((i+1)*sizeof(char)) );
    sec = pipx;
    //add bitstr[b] to second array
    sec[i] = (char)bitstr[b] + '0';
    i++;

    for (m = 0; m < k; m++){
        printf("codex[m].bitx:%s", codex[m].bitx);
        printf("sec:%s|\n", sec);
        printf("seclen: %i", (int)strlen(sec));
        printf("codex[m].bitxlen: %i\n", (int)strlen(codex[m].bitx));
        if ((char*)sec == (char*)codex[m].bitx){
            printf("This should output: %s", sec);
            printf("Here ---------------------- Here");
            //allocate the second array to zero
            i=0;
            sec = (char*)malloc(0);
        }
    }
}
Community
  • 1
  • 1
Netmaxweb
  • 21
  • 2

3 Answers3

4

in order to compare strings, you need to use strcmp instead of ==

== verifies they point to the same address, while strcmp will compare the two char* and return true if every character matches until it hits \0

Majid Laissi
  • 19,188
  • 19
  • 68
  • 105
1

That's because you are comparing to see if the two variables point to the same memory address, not if the information at the two memory addresses is the same. always use strcmp

Ionut Hulub
  • 6,180
  • 5
  • 26
  • 55
0

You are comparing literal pointer values rather than the strings those pointers point to.

As others have said, lookup strcmp() and friends.

John3136
  • 28,809
  • 4
  • 51
  • 69