【问题标题】:Request for member in something not a struct or union请求非结构或联合的成员
【发布时间】:2014-02-13 05:17:43
【问题描述】:

所以我为 qsort 定义了函数比较,但显示以下错误:

1.c: In function ‘compare’:
1.c:235:7: error: request for member ‘count’ in something not a structure or union
1.c:235:17: error: request for member ‘count’ in something not a structure or union
1.c:237:12: error: request for member ‘count’ in something not a structure or union
1.c:237:23: error: request for member ‘count’ in something not a structure or union

有人知道为什么吗?我的意思是这不是我拼错了名字:

struct word
{
  char wordy[100];
  int count;
};


int compare(const void* a, const void* b)
{

const struct word *ia = (const struct word *)a;
const struct word *ib = (const struct word *)b;

if(*ia.count>*ib.count)
    return 1;
else if(*ia.count==*ib.count)
    return 0;
else
    return -1;
}

【问题讨论】:

  • 现在,您已经编辑了原始帖子以修复拼写错误。将来,复制/粘贴真实来源 - 不是您最好的回忆。
  • 建议同时显示您的qsort() 电话。根据您要排序的内容,比较功能可能会有其他问题。
  • 更改为(*ia).countia->count
  • rjv答错了。

标签: c function struct qsort


【解决方案1】:

然而,你确实拼错了名字:(

您在 compare 函数中引用 words 并在其外部定义 word

[编辑]
你说it's defined as a global struct。在哪里?您在此处复制的源没有可发现的 words 定义
[/编辑]

由于您已从原始形式编辑帖子,您的问题现在与 rullof 已发布一样 - 您正在使用 . 访问 -> 项目

【讨论】:

  • 但是在程序一开始就定义为全局结构体,而且必须是(由于其他功能)。编辑:lmao,这个名字是真的,但它仍然是同样的错误。
  • 嗯...它所在的程序有大约 10 个不同的函数,我在程序的开头编写了这个结构,而不是在其中任何一个中 - 就在 #include stdio.h 等之后,是还不够吗?
  • @deviance - 仔细阅读凯文所说的话。他的回答是正确的,并指出words(在比较函数中)没有在任何地方定义。在全局范围内,您已经定义了word。只需在比较函数中将words 更改为word
  • 它没有解决问题,修复后错误是一样的。
  • @deviance - 在人们试图回答您的问题时编辑原始帖子会令人困惑,应该避免。
【解决方案2】:

问题在于iaib 是指向const struct word 的指针。要访问结构的成员,我们使用指向它的指针 (->) 而不是点 .

另外,在声明 iaib 时,请确保拼写结构名称,方法与上面声明的方式相同。

所以你的代码应该是:

struct word
{
  char wordy[100];
  int count;
};


int compare(const void* a, const void* b)
{

const struct word *ia = (const struct word *)a;
const struct word *ib = (const struct word *)b;

if(ia->count > ib->count)
    return 1;
else if(ia->count == ib->count)
    return 0;
else
    return -1;
}

【讨论】:

  • 谢谢!将 *ia.count 更改为 ia->count 修复它
猜你喜欢
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多