0

作为一个更大项目的一部分,我正在尝试编写一个 C 函数,该函数在已实现的排序链表中搜索 struct 中的值olnode。但是,我收到了一些错误。我是 C 新手,我正在为指针和双指针以及何时使用什么而苦苦挣扎,所以我认为这是问题的一部分,但我不确定如何解决这个问题。包括所有必要的标题。这是在使用 cc 作为编译器的 Minix 2.0.4 上。

我可以提供任何额外的必要代码;因为我不熟悉 C,所以我不确定我需要展示多少,所以我提供了我认为需要的东西,仅此而已。

全局代码(标题除外):

#define POOLSZ 53
struct olnode {
    int eventnr;
    int eventfq;
    struct olnode *next;
};
typedef struct olnode olnode;
olnode pool[POOLSZ];
olnode *avail;    /* points to first available node */

返回错误的函数(搜索传递的 int,完成后*current应该是olnode保存当前值的函数):

void
srchfreq(olnode *list, int xfrequency, olnode **current)
{
    olnode *previous, *newnext;

    while(current->eventfq > xfrequency) {
        *previous = &current;
        *newnext = current->next;
        *current = *newnext;
    }
}

srchfreq()(在不同的函数中)的函数调用:

/* *list points to the first node in the list
   (*current).eventfq is the value being searched for
*/

srchfreq(*list, (*current).eventfq, &current);

错误(行号被编辑为相对于srchfreq()上面给出的行):

line 6: illegal use of selector eventfq
line 7: cannot convert pointer to struct
line 8: illegal use of selector next
line 8: cannot convert pointer to struct
line 9: cannot convert struct to pointer
4

3 回答 3

1

错误,按出现顺序:

  • 由于current是一个指向a的指针olnode,它不能直接引用任何字段;但*current可以。
  • *previous是一个olnode&current是一个指向一个指向一个指针的指针olnode
  • 查看第一个错误
  • *newnext是一个olnode
  • *current是一个指针olnode
于 2015-01-30T18:39:08.340 回答
1
void
srchfreq(olnode *list, int xfrequency, olnode **current)
{
    olnode *previous, *newnext;

    while((*current)->eventfq > xfrequency) {
        previous = *current;
        newnext = (*current)->next;
        *current = newnext;
    }
}

第二部分取决于参数的类型。如果list声明为olnode *list,则无需取消引用它,因为函数需要一个指针。第二个和第三个参数是错误的(其中一个 - 确定我们需要知道哪个是如何current声明的)。

于 2015-01-30T18:35:13.350 回答
1

current具有 typeolnode**或指向 oldnode 的指针。要获取指向 olnode 的指针,请取消引用该指针一次:

*current;

要获取 olnode 本身,请取消引用您从取消引用指向指针的指针中获得的指针

**current;

所以在你的情况下,抓住这个领域eventfq

(**current).eventfq

C 还提供了快捷方式的操作(*ptr).field,完全等价于prt->field.

在您的情况下,您可以将其应用于

(*current)->eventfq
于 2015-01-30T18:35:22.220 回答