#c strcmp() isn't working as it should

2019-09-07 17:39发布

问题:

I want to compare between two char* so i do it with strcmp, look, in debugging mode, both char* in strcmp gets the same value and still it wont return 0, and it jumps over the if() condition instead of entering it:

here pic from the debugger: http://img405.imageshack.us/img405/5218/111fi.jpg

Company FindCompany(CompanyL pcompanyList, int companyIdentityDigit) 
{
    Company companyFound;
    char *psearchWord;
    psearchWord = (char*)malloc(10*sizeof(char));

    switch(companyIdentityDigit) {
        case 0: 
            strcpy(psearchWord , "Pelephone");
            break;
        case 2: 
            strcpy(psearchWord , "Cellcom");
            break;
        case 4: 
            strcpy(psearchWord , "Orange");
            break;
    }

    while(pcompanyList->next != NULL)   {
        if(strcmp(pcompanyList->thisCompany->pcompany , psearchWord) == 0)  {
            free(psearchWord);
            return pcompanyList->thisCompany;
        }
        pcompanyList = pcompanyList->next;
    }
    free(psearchWord);
    return NULL;
}

why is it??

回答1:

Try a simple for loop to print out the characters in pcompanyList->thisCompany->pcompany one at a time:

for (int x = 0; x < strlen(pcompanyList->thisCompany->pcompany); x++)
    printf("%c ", pcompanyList->thisCompany->pcompany[x]);

You can do this or check the length of each string to make sure there aren't hidden characters that aren't showing up in the debugger when you check the strings.



标签: strcmp