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

六眼飞鱼酱① 提交于 2019-12-25 09:48:37

问题


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.



来源:https://stackoverflow.com/questions/4300325/c-strcmp-isnt-working-as-it-should

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!