Ok.. here's the whole program:
(I know my checks for NULL after malloc and realloc are screwy, but i dont think that would be the cause of the problem.)
Code:
#include <stdlib.h>
#include <stdio.h>
typedef struct tableItem {
char myChar;
int freq;
} tableItem;
static int tableCount = 0;
tableItem** freqTable;
/*returns index in freqTable of either next open spot or where current character is */
int findInTable(char toFind)
{
int index = 0;
while(index < tableCount && freqTable[index] != NULL)
{
if(freqTable[index]->myChar == toFind)
break;
else
index++;
}
return index;
}
/*adds character to table by getting index from findInTable*/
void addToTable(char toAdd)
{
int where = 0;
void* temp;
where = findInTable(toAdd);
if((temp = realloc(freqTable, tableCount*sizeof(tableItem*) + sizeof(tableItem*))) == NULL)
{
free(freqTable);
printf("screw it");
exit(1);
}
freqTable = temp;
if(freqTable[where] == NULL)
{
if((temp = malloc(sizeof(tableItem))) == NULL)
{
free(freqTable);
printf("screw it");
exit(1);
}
freqTable[where] = temp;
freqTable[where]->myChar = toAdd;
freqTable[where]->freq = 1;
tableCount++;
}
else
{
freqTable[where]->freq++;
}
}
void printTable()
{
int index = 0;
tableItem* temp;
while(index < tableCount && freqTable[index] != NULL)
{
temp = freqTable[index];
printf("[%c:%d]\n", temp->myChar, temp->freq);
index++;
}
}
/* ok i commented out that part and just made it one line of code, it works but qsort is switching all the wrong things, doesn't sort it. Ill put the output at the bottom */
int compareT(const void *a,const void *b)
{
/*tableItem * const *first = a;
tableItem * const *second = b;
int retVal;
retVal = *(*second).freq - *(*first).freq;
return retVal;*/
return ((*(tableItem*)a).freq - (*(tableItem*)b).freq);
}
int
main(int argc, char **argv)
{
addToTable('a');
addToTable('b');
addToTable('c');
addToTable('f');
addToTable('c');
addToTable('a');
addToTable('f');
addToTable('a');
addToTable('f');
addToTable('z');
addToTable('u');
addToTable('u');
addToTable('r');
addToTable('e');
addToTable('r');
addToTable('r');
addToTable('r');
addToTable('r');
addToTable('r');
printTable();
printf("-------------\n");
qsort((void *)freqTable, tableCount-1, sizeof(freqTable[0]), compareT);
printTable();
return 0;
}
Ok now the program doesn't core dump, but it doesn't sort either, here is my output:
[a:3]
[b:1]
[c:2]
[f:3]
[z:1]
[u:2]
[r:6]
[e:1]
------------- /*sort occurs here */
[c:2]
[b:1]
[a:3]
[z:1]
[r:6]
[u:2]
[f:3]
[e:1]
thanks for any help!!