Search code examples
cstrcmp

Comparing chars[] does not work


I have problem with strcmp function (same question is here, but there aren't good answers). If I compare 2 same strings, but one string is from structure, this string is wrongly "translated" to assembly code. Every char[] from structure are random 3 characters. Picture of strcmp.asm

#define CONS 60

typedef struct LinkCity{
    char city[CONS];           // i get this char[] from file by using fgets()
    struct LinkCity* next;
} tLinkCity;
/***************************************/
    typedef struct {
        int NumberOfCity;
        tLinkCity* Link;
        double** distances;
    } tDatabaze;
/***************************************/
int GetIndexOfCity(tDatabaze* db, char * city){

    printf("%s %s", db->Link->city, city); //   > Barcelona\n Barcelona (yes, here is a newline)
    str = strcmp(db->Link->city, city);    //   str = 1  (=it should be 0)
}

Solution

  • try removing the newline from the end of the string before comparing , here's a simple function to does that :

    void removeNLine(char* string)
    {
            int i ;
            for(i = strlen(string) ; i > 0 ; i--)
                   if(string[i] == '\n')
                         string[i] = '\0';
    }