c - C中的动态数组升序排序

标签 c arrays dynamic

我正在尝试对动态数组列表进行排序,但它不起作用,而且我不明白我应该怎么做。这是我到目前为止所做的:

    void ascending_sort(Controller* ctrl)
    {
    int i,j;
    Cost* aux;
    DynamicVector* c=getAllCosts(ctrl);
    for(i=0;i<getLen(c)-1;i++)
    {
        Cost* cost;
        for(j=i+1;j<getLen(c);j++)
        {
            if(cost[i].sum < cost[j].sum)
            {
                    aux=cost[i]; //error
                cost[i]=cost[j];
                cost[j]=aux; //error
            }
        }
    }
}

结构如下:

typedef struct{
    char* day;
    char* type;
    int sum;
}Cost;

我该如何解决?当我声明“Cost* aux”时,我认为我做错了什么。我希望你能帮助我!

编辑:我更新了排序功能的新代码。现在它不打印我想要的东西。它打印“Cost 1”,仅此而已,然后我收到一个“结束程序”窗口,该窗口停止了所有操作。可能是什么问题?

这是新的排序算法:

void ascending_sort(Controller* ctrl)
        {
        int i,j;
        DynamicVector* c=getAllCosts(ctrl);
        for(i=0;i<getLen(c)-1;i++)
        {
            Cost* cost=getElementAtPosition(c,i); //returns element on position
            for(j=i+1;j<getLen(c);j++)
            {
                if(cost[i].sum < cost[j].sum)
                {
                const 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!");
}

这是从 Controller 调用排序函数到控制台的函数:

void AscendingSort(Console* console)
{
    ascending_sort(console->ctrl);
}

最佳答案

是的,当您需要实际值时,您正在使用指向 Cost 的指针。最里面的范围应该是这样的:

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

请注意,我没有看到(或理解)costCost 数组和 c 之间的关系,它是输入 DynamicVector * 以及您在循环中使用的长度。

此外,您的排序算法不是很好;你应该只使用 qsort()

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

相关文章:

如果符号之间没有空格,C 计数字程序就可以工作,为什么?

arrays - 在哪里放置对结构数组进行操作的代码?

javascript - 动态 DOM 操作函数 : How To Improve It, 我应该使用它吗?它在这里做什么?

function - 动态调用功能

c - Lxpanel 插件和线程

c - 任何优化都会删除代码(指向数组的 volatile 指针)

c++ - 尝试创建队列 - C++ 崩溃问题

c++ - 数组中的错误功能排序

c# - 将 IEnumerable 动态转换为 IQueryable 或使用 LINQ 表达式动态调用 AsQueryable

c - "malloc(sizeof(struct a *))"和 "malloc(sizeof(struct a))"是一样的吗?