【问题标题】:Prototype Declaration Error when Implementing a remove function for a Queue为队列实现删除函数时出现原型声明错误
【发布时间】:2016-01-20 02:43:19
【问题描述】:

我正在尝试在 C 中实现一个队列,并且在我的 remove(q) 方法中得到了一个原型声明。我想知道我在这里做错了什么,我正在使用旧版本的队列实现作为练习,但不能把它放在一起。

#include <stdio.h>

#define MAXQUEUE 100
#define TRUE  (1==1)
#define FALSE (1==0)

struct queue {
    int items[MAXQUEUE];
    int front, rear;
};

empty(pq)
struct queue *pq;
{
    return ((pq->front == pq->rear) ? TRUE : FALSE);
}

remove(pq)
struct queue *pq;
{
    if (empty(pq)) {
        printf("queue underflow\n");
        exit(1);
    }

    if (pq->front == MAXQUEUE - 1)
        pq->front = 0;
    else
        (pq->front)++;
    return (pq->items[pq->front]);  
}

int main() {
    struct queue q;

    q.front = q.rear = MAXQUEUE - 1;

    if (empty(q)) {
        printf("hello");
    } else
        printf("\n sod off\n");

    return 0;
}

【问题讨论】:

  • 我认为您声明函数的语法可能是错误的。它应该是return_type function_name(arg_type argname, ) { function_body }。所以像struct queue * empty(struct queue * pq) { ... }

标签: c compiler-errors queue


【解决方案1】:

你的函数不是函数。您需要调整它们以将队列作为参数并返回您的值,如下所示:

int empty(struct queue *pq)
{
    return ((pq->front == pq ->rear) ? TRUE : FALSE);
}

int remove(struct queue *pq)
{
    if(empty(pq)){
        printf("queue underflow\n");
        exit(1);
    }

    if(pq->front == MAXQUEUE-1)
        pq->front = 0;
    else
        (pq->front)++;
    return (pq->items[pq->front]);  
}

将这些更改与您的主要 (if (empty(q) -> if (empty(&amp;q)) 中的一项更改一起进行编译并输出 hello

【讨论】:

  • OP 正在从一些非常古老的源代码中复制。此语法曾经是有效的 K&R 语法,但在 C99 中已被弃用。
【解决方案2】:

如果你这样声明你的函数会怎样:

void
empty(struct queue *pq)
{
    ...
}

void
remove(struct queue *pq)
{
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多