1

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.

17
  • How are you printing them? Show us that code too. Commented Jun 17, 2014 at 10:08
  • 1
    For one, the logic is incorrect if you fed "ca" and "cat" to this function. Identical prefix of non-identical strings will report as equal; but they're not. Commented Jun 17, 2014 at 10:10
  • 1
    @MattMcNabb, I don't think so, this function here returns 0 as soon as one of the strings is finished. Commented Jun 17, 2014 at 10:13
  • 3
    Your casts for the array are completely screwed. Commented Jun 17, 2014 at 10:14
  • 2
    char * s1 = *(char **) p1; char * s2 = *(char **) p2; Commented Jun 17, 2014 at 10:20

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.