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);
        }
    }
}
4

3 回答 3

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

于 2012-09-26T01:47:49.860 回答
1

那是因为您正在比较两个变量是否指向相同的内存地址,而不是两个内存地址处的信息是否相同。总是使用 strcmp

于 2012-09-26T01:48:56.787 回答
0

您正在比较文字指针值而不是那些指针指向的字符串。

正如其他人所说,查找strcmp()和朋友。

于 2012-09-26T01:49:06.920 回答