Home > OS >  Why strcmp doesn't work in Online GDB compiler?
Why strcmp doesn't work in Online GDB compiler?

Time:11-10

Does Online GDB have any problems with string.h library?

void insertionSort( char *ptrArr[] )
{
    for( int i = 1; i < ROW; i   )
    {
        char *temp = ptrArr[i];
        int j;
        for( j = i - 1; j >= 0 && (strcmp(temp, ptrArr[j]) == -1); j-- )
            ptrArr[j   1] = ptrArr[j];
        ptrArr[j   1] = temp;
    }
}

The above code doesn't work in online GDB. There are no changes in output array of pointers sorting. But It works fine on my local compiler.

CodePudding user response:

Your comparison is wrong: instead of

(strcmp(temp, ptrArr[j]) == -1)

You should write

(strcmp(temp, ptrArr[j]) < 0)

Indeed, strcmp return a positive or negative value (or 0), not necessary -1 or 1 (or 0).

From man strcmp:

The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

  • Related