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;
}
}