c - C中动态数组的排序算法

标签 c arrays sorting dynamic struct

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

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;

最佳答案

您正在尝试以数组形式访问 cost,在排序代码中

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

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

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

关于c - C中动态数组的排序算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15478446/

相关文章:

python - 使用 python 2 根据自定义行顺序对 2D 锯齿状列表进行排序

ruby - 你能用 Ruby 优化这个降序排列的数组吗?

c - C调用时如何逐行执行Lua函数

c - POSIX 共享内存 + 目录

c - 一个简单的 C 程序的奇怪输出

javascript - 为什么我不能用forEach来遍历一棵树?

c - 如何在 ANSI C 中使用指向两个数组中的冒泡排序值的指针?

arrays - 在 Swift 中初始化固定大小的数组时出现类型错误

c - "C"函数内的数据操作

java - JTable 排序不显示图像