【问题标题】:Why qsort cause error in gcc 6.3.0 by using typedef enum?为什么 qsort 通过使用 typedef 枚举在 gcc 6.3.0 中导致错误?
【发布时间】:2018-10-11 02:34:56
【问题描述】:

我正在研究强连通分量 (SCC) 算法。

所以,我使用qsort 函数按递增顺序对顶点进行排序。

为了使用qsort,我制作了自己的比较函数并使用了typedef enum{false,true} bool。

VS2017 IDE 编译成功,但具有 gcc 6.3.0 的 MinGW 导致如下错误。

我的CreateSorted和qsort比较函数就是这些代码。

// qsort compare function, descending order
bool cmp(const void *p1, const void *p2)
{
    VF* vf1 = (VF*)p1;
    VF* vf2 = (VF*)p2;
    return vf2->f - vf1->f;
}

// Create sorted vertices array of VF structure
// For DFS of decreasing finish time vertex
VF* CreateSorted(adjList* adj)
{
    VF *sorted_vertices = (VF*)malloc(sizeof(VF)*(adj->vertexNum+1));

    for (int i = 1; i <= adj->vertexNum; i++) {
        Node* current = adj[i].nodeList;
        sorted_vertices[i].v = current->v;
        sorted_vertices[i].f = current->f;
    }
    qsort(sorted_vertices+1, adj->vertexNum, sizeof(VF), cmp);
    return sorted_vertices;
}

我真正好奇的是typedef enum{false, true} bool导致错误的原因。

【问题讨论】:

  • 答案是正确的。但是,您的 cmp 函数也是错误的,因为您声明它返回 true 和 false,当函数返回的值可能小于 0、大于 0 或等于0。

标签: c typedef gcc-warning qsort


【解决方案1】:

qsort 的第四个参数应该是指向具有以下原型的函数的指针:

int compar (const void* p1, const void* p2)

你的函数原型是:

bool compar (const void* p1, const void* p2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    相关资源
    最近更新 更多