【问题标题】:Why do we need & at some place and not in the other place when calling functions when both are taking pointer type arguments?为什么我们在调用函数时在某个地方需要 & 而不是在另一个地方需要指针类型参数?
【发布时间】:2016-12-18 08:11:45
【问题描述】:
    #include <stdio.h>
    #include <stdlib.h>
    #define QUEUESIZE 30

    int qfull(int *r)
    {
        if(*r == QUEUESIZE-1)
            return 1;
        else
            return 0;
    }


    int qempty(int *f,int *r)
    {
        if(*f > *r)
            return 1;
        else
            return 0;
    }

    void enqueue(int item,int q[], int *r)
    {
        if(qfull(r))
        {
            printf("Cannot Insert. Queue full.\n");
            return;
        }

        (*r)++;
        q[*r] = item;
    }

    void dequeue(int q[], int *r, int *f)
    {
        if(qempty(f,r))
        {
            printf("The queue is empty\n");
            return;
        }

        int item_deleted = q[*f];
        (*f)++;

        if(*f > *r)
        {
            *f = 0;
            *r = -1;
        }
    }

    void display(int q[], int *f, int *r)
    {
        if(qempty(f,r))
        {
            printf("Nothing to display.\n");
            return;
        }

        for(int i=*f; i<=(*r); i++)
        {
            printf("%d\n",q[i]);
        }
    }

    int main()
    {
        int f = 0;
        int r = -1;

        int q[QUEUESIZE];

        int item,choice;

        while(1)
        {
            printf("Enter a choice: \n");
            printf("1. Enqueue\n");
            printf("2. Dequeue\n");
            printf("3. Display\n");
            printf("4. Exit\n");

            scanf("%d",&choice);

            switch(choice)
            {
                    case 1:
                    printf("Enter an item: \n");
                    scanf("%d",&item);
                    enqueue(item,q,&r);
                    break;

                    case 2:
                    dequeue(q,&r,&f);
                    break;

                    case 3:
                    display(q,&f,&r);
                    break;

                    default: exit(0);
            }
        }   
    }

这是我的代码。 当我在主程序中调用入队函数并且我使用 r 而不是 &r 时,它给了我一个warning

当我在 enqueue 的定义中调用 qfull() 函数时使用 &r 时,它给了我这个warning

我想知道为什么?

【问题讨论】:

    标签: c pointers data-structures queue function-pointers


    【解决方案1】:

    当我在主程序中调用入队函数时

    int main()
    {
        ...
        int r = -1;
          ...
          enqueue(item,q,&r)
    

    在 enqueue 的定义中调用 qfull() 函数

    void enqueue(int item,int q[], int *r)
    {
        if(qfull(r))
    

    int rint * r 没有定义相同的 r

    前者是int,后者是指向int的指针。

    【讨论】:

    • 你能不能更恰当地回答一下?
    • 两个参数都包含指向 int 的指针。请仔细阅读我的问题。
    • @AshwaniJha:在第一种情况下,您传递r,这是一个int,在第二种情况下,您通过r 作为int*。请查看我的更新答案。
    猜你喜欢
    • 2016-03-31
    • 2013-05-28
    • 2021-09-23
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多