I am trying to sort a Dynamic Array that contains Costs as elements. This is my sorting function:
void ascending_sort(Controller* ctrl) //the function is in the controller
{
int i,j;
DynamicVector* CostList=getAll(ctrl->repo); //the getALL function returns the CostList that has Costs as elements
for(i=0;i<getLen(CostList)-1;i++)
{
Cost* cost=(Cost*)getElementAtPosition(CostList,i); //getElementAtPosition returns the Cost at a certain position
for(j=i+1;j<getLen(CostList);j++)
{
Cost* cost1=(Cost*)getElementAtPosition(CostList,j);
if(cost->sum > cost1->sum)
{
Cost aux=cost[i];
cost[i]=cost[j];
cost[j]=aux;
}
}
}
}
The problem is when I want to print the costs. If I print them before sorting, everything goes right and prints the costs. If I sort the list and then print the sorted Costs I get a "Close Program" error, and the program crashes. This is the print function:
void PrintCosts(Console* console)
{
DynamicVector* CostList=getAllCosts(console->ctrl);
if (getLen(CostList))
{
int i;
for(i=0;i<getLen(CostList);i++)
{
printf("\nCost %d\n\n",i+1);
Cost *c=(Cost*)getElementAtPosition(CostList,i);
PrintCost(c);
}
}
else printf("No cost in the list!");
}
This is the struct:
typedef struct{
int id;
char* day;
char* type;
int sum;
}Cost;
This is the sorting function that is called in the console:
void AscendingSort(Console* console)
{
ascending_sort(console->ctrl);
}
This is a function that returns a Cost* type:
Cost* initCost(char* day, char* type, int sum)
{
Cost* c=(Cost*)malloc(sizeof(Cost));
if(strlen(day)>0 && strlen(day)<=10)
{
c->day = copyString(day);
}
else
{
c->day=0;
}
if(strlen(type)>0 && strlen(type)<=20)
{
c->type = copyString(type);
}
else
{
c->type=0;
}
if(sum>0)
{
c->sum= sum;
}
return c;
}
Console:
Console* initConsole(Controller* ctrl)
{
Console* console=(Console*)malloc(sizeof(Console));
console->ctrl=ctrl;
return console;
}
getElementAtPosition
TElem getElementAtPosition(DynamicVector* v, int pos)
{
if(v->elem[pos])
return v->elem[pos];
else
return 0;
}
typedef void* TElem;
Console-type and the definition ofgetElementAtPosition?void*all over the place. Your errors would probably be caught be the compiler if you defined explicit types for your system. You are asking the compiler to ignore type mismatches by casting tovoid*:)