shoham
shoham

Reputation: 812

Comparing two strings in C (string pointers)

I have a string array that is declared like this:

    char * d[] = {"bca", "abc", "cba", "abcd"};

I'm trying to compare d[1] to d[2] in a generic compare method (using void *):

int compareString(void * p1, void *p2)
{
    char * s1 = (char *) p1;
    char * s2 = (char *) p2;
    while(*s1 && *s2)
    {
        if(*s1 > *s2) return 1;
        else if(*s2 > *s1) return -1;
        s1++;
            s2++;
    }
    return 0;
}

For some reason when I try and print s1\s2 I get some gibberish. Note: It does work if the array is declared like this:

char e[][5] = {"bca", "abc", "z", "dca", "cba"};

EDIT:

Code where I call the function:

void sort(void * arr, int arrLength, int sizeOfElement, int (*compare)(void *, void *))
{
    int i, j;
    for(i = 0; i < arrLength; i++)
        for(j = 0; j < arrLength - 1; j++)
            if(compare(((char *)arr + j * sizeOfElement), ((char *)arr + (j + 1) * sizeOfElement)) > 0) swap(((char *)arr + j * sizeOfElement), ((char *)arr + (j + 1) * sizeOfElement), sizeOfElement);
}

And I look at s1 and s2 via the debugger.

What am I doing wrong?

Thanks.

Upvotes: 1

Views: 517

Answers (1)

Omer
Omer

Reputation: 96

For array 'e' this is the cmp:

    int cmpS1(void *aa,void *bb){
    int r;
    r=strcmp((char*)aa,(char*)bb);
    return r;
    }

And for array 'd' you need this cmp:

int cmpS2(void *aa,void *bb){
    char* s1=*(char**) aa; char* s2=*(char**) bb;
    while(*s1 && *s2){
        if(*s1 > *s2) return 1;
        else if(*s2 > *s1) return -1;
        s1++;
        s2++;
    }
    return 0;
}

Upvotes: 2

Related Questions