【发布时间】:2013-03-18 13:49:14
【问题描述】:
我正在尝试对包含成本作为元素的动态数组进行排序。这是我的排序功能:
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;
}
}
}
}
问题是当我想打印成本时。如果我在分类之前打印它们,一切都会正常并打印成本。如果我对列表进行排序,然后打印排序后的成本,则会出现“关闭程序”错误,并且程序崩溃。 这是打印功能:
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!");
}
这是结构:
typedef struct{
int id;
char* day;
char* type;
int sum;
}Cost;
这是在控制台中调用的排序函数:
void AscendingSort(Console* console)
{
ascending_sort(console->ctrl);
}
这是一个返回 Cost* 类型的函数:
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* 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 的定义和getElementAtPosition的定义吗? -
你到处乱扔
void*。如果您为系统定义了显式类型,您的错误可能会被编译器捕获。您要求编译器通过转换为void*来忽略类型不匹配:)
标签: c arrays sorting dynamic struct