1

我正在尝试对包含成本作为元素的动态数组进行排序。这是我的排序功能:

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

获取元素位置

TElem getElementAtPosition(DynamicVector* v, int pos)
{
    if(v->elem[pos])
        return v->elem[pos];
    else
        return 0;
}

typedef void* TElem;
4

2 回答 2

1

您正在尝试cost在排序代码中作为数组访问

Cost  aux=cost[i];
cost[i]=cost[j];
cost[j]=aux;

这是不正确的,假设getElementAtPosition()返回指向一个项目的指针而不是可顺序访问的项目数组,即数组。

您只能通过指针通知访问一个元素,例如cost->sum,而不是cost[i].sum除非i==0

于 2013-03-18T14:04:52.457 回答
0

听起来你遇到了段错误。您没有显示返回 Cost* 的函数,并且您在取消引用之前从未验证 Cost*。也许那个区域有问题?我想我需要更多的源代码来验证这一点。

我也注意到了这一点。

for(i=0;i<getLen(CostList);i++)
{
    printf("\nCost %d\n\n",i+1);
    Cost *c=(Cost*)getElementAtPosition(CostList,i); <-- typeof(C) == Cost*
    PrintCost(c);  <-- typeof(C) == Console*
}

您将变量c用作 aCost*和 a Console*。这不是一种类型安全的做事方式,所以我猜你这里有一些错误。虽然没有更多代码,但无法分辨:)

于 2013-03-18T14:01:40.570 回答