【问题标题】:qsort in C with structures, some problemsC中的qsort结构,一些问题
【发布时间】:2013-11-29 01:20:43
【问题描述】:
void sortSchedule (struct event schedule[], int n)
{
    qsort(schedule, n, sizeof(struct event), compare());
}

int compare(const void * a, const void * b)
{
    const struct event *evA = a;
    const struct event *evB = b;

    int startA = evA.start.hour*60 + evA.start.minute;
    int startB = evB.start.hour*60 + evB.start.minute;

    return ( startA - startB );
}

我的结构

struct tod {
  int hour, minute;
};


struct event {
  struct tod start, end;
};

仅使用compare 而不是compare(),编译器似乎将其视为变量。

其次,我想知道我的比较功能是否正确?由于我从编译器中得到了一些错误,更具体地说是以下

Error: request for member 'start' in something not a structure or union

^ 该行出现错误int startA = evA.start.hour*60 + evA.start.minute;

所以我假设它认为 evA 不是一个结构,即使我明确声明它也是如此。这可能是因为我没有正确声明它,任何帮助将不胜感激:)

【问题讨论】:

  • evAevB 是指针,因此您需要使用 evA->start 取消引用
  • 我之前试过,这是我得到的错误error: invalid type argument of '->' (have 'const struct tod')
  • evA->start.hour*60 start 是一个结构,所以你仍然使用.

标签: c sorting struct


【解决方案1】:

由于evAevB 是指针,因此您必须使用evA->member 而不是evA.member

【讨论】:

  • 我之前试过,这是我得到的错误error: invalid type argument of '->' (have 'const struct tod')
  • 由于你的成员不是指针,它应该是这样的:evA->start.hour
  • 好吧,忘记了。比较问题呢?应该是compare 还是compare()?前者给了我一个错误。其次,程序似乎崩溃了,编译器没有出现太多错误。所以我删除了int startAint startB这两条线,然后尝试了下面的printf("%d", evA->start.hour);,这也会导致程序崩溃。
  • 您是否为您的函数添加了前向声明int compare(const void * a, const void * b); 应该放在你调用 qsort 之前的某个地方,例如在你的#includes 之后。然后它应该被传递为compare,而不是compare()
【解决方案2】:

如果您使用指针执行此操作,则应使用-> 来引用结构成员:

int startA = evA->start.hour*60 + evA->start.minute;
int startB = evB->start.hour*60 + evB->start.minute;

您对qsort 的电话应该是:

qsort(schedule, n, sizeof(struct event), compare);

因为第四个参数是一个指向函数的指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    相关资源
    最近更新 更多