David Scheibe
David Scheibe

Reputation: 63

setting an array of pointers to pointers, point to a pointer in another array

The program I am working on uses qsort, and my own compare function, to sort a group of words read in through standard input. I am putting each character into an array of pointers to characters as below.

The array now has a bunch of characters, for example - "\0The\n\0brown\n\0fox\n\0is\n\0lazy\n"

I am trying to create another array of pointers to pointers where each element of this new array points to the first letter (this case the null character) of each word. So element 0 points to the first \0 and element 1 points to the next \0. I'm not sure if there is a small syntax error I have or if I have the wrong idea, but something keeps going wrong because the output is never in the correct order. Code below:

int buffersize = 2048;
int count = 0;
char* p = (char*) malloc(sizeof(char) * buffersize);
int c;
do{
    c = getchar();
    p[count++] = (char)c;
    if (count == buffersize)
    {
        p = (char*) realloc(p, buffersize * 2);
        buffersize *= 2;
    }
}while (c != EOF);
p[count-1] = '\n';
int i = 0;
int a = 1;
char ** pp = (char**) malloc(sizeof(char*) * count);
pp[0] = &p[0];
for (i; i < count; i++)
{
    if (p[i] == '\n')
    {
        while (p[i+1] == '\n')
        {i++;}
        if ( i != (count-1) )
        {
            pp[a++] = &p[i+1];
        }
    }
}
qsort (pp, (a-1), sizeof(char*), compare);

My compare function

int rot13cmp (const void* c, const void* d)
{
    const char* a = (const char*)c;
    const char* b = (const char*)d;
    if (a[0] == '\0' && b[0] == '\t')
    {
        return -1;
    }
    else if (a[0] == '\t' && b[0] == '\0')
    {
        return 1;
    }
    int k = 0;
    for (;;k++)
    {
        if (a[k] == '\n' && b[k] != '\n')
            return -1;
        if (a[k] != '\n' && b[k] == '\n')
            return 1;
        if (a[k] == '\n' && b[k] == '\n')
            return 0;
        int one = (int)a[k];
        int two = (int)b[k];
        int difference = a[k] - b[k];
        if (difference != 0)
            return difference;
    }
}

Upvotes: 2

Views: 84

Answers (1)

WhozCraig
WhozCraig

Reputation: 66234

Your compare function is incorrect. If the sequence being sorted is a sequence of pointers, then the addresses passed to your compare are addresses of the pointers; not addresses in the pointers.

replace this:

const char* a = (const char*)c;
const char* b = (const char*)d;

with this:

const char * const* lhs = c;
const char * const* rhs = d;
const char* a = *lhs;
const char* b = *rhs;

or simplify as desired. The rest of your function should work (at least as well as you wrote it, I never checked it for accuracy except to say that both one and two are not used and should be removed, and your function should have a outer-most return 0; to avoid an undefined result if the strings are identical).

Upvotes: 1

Related Questions