使用结构化编程实现队列

时间:2018-09-26 01:00:02

标签: arrays pointers queue structure

我是C语言的新手,所以我们的课程开始使用结构化编程。就参数#而言,一切都很好,但是我很难理解错误消息。尝试调用入队和出队时,它说int不能转换为int *。当涉及结构化编程以及传递值和地址时,我很难理解指针。

bool Enqueque(int queue[], int* front, int* rear, int intialSize);
int Dequeque(int queue[], int* front, int* rear);
int GetCurrentSize(int queue[], int* front, int* rear);
int toString(int queue[], int* front, int* rear);

int main()
{
    bool enqueueResult, dequeueResult, ifEmpty;
    int UserOption = 0;  
    int initialSize = 10;

    int* queue = (int*)malloc( initialSize * sizeof(int) );
    for(int i = 0; i<initialSize; i++)
        queue[i] = 0;

    int* front, rear;


    printf("This program implements Queues using structured programming. Enter "
            "a number from 1 to 4 . \n"
            "1. To enqueue a number \n"
            "2. To dequeue a number \n"
            "3. To get the current size of the queue \n"
            "4. To see the contents within the queue \n");
    scanf( "%d",UserOption );

    switch(UserOption)
    {
        case 1:
            enqueueResult = Enqueque(queue, front, rear, initialSize);

            if(enqueueResult == true)
                printf( "The number has been put into the queue!");
            else
                printf("The number was not able to be enqueued!");
            break;

        case 2:
            dequeueResult = Dequeque( queue, front, rear );

            if(dequeueResult == true)
                printf( "The number has been dequeued!");
            else
                printf("The number wasn't able to be dequeued!");
            break;

        case 3:
            printf( "The current size of the queue is: " + GetCurrentSize( queue, front, rear) );
            break;
    }
}

1 个答案:

答案 0 :(得分:0)

对于以后的评论,请添加完整的错误消息和编译器警告。但是,我认为问题出在您的scanf()

您写道:

scanf( "%d",UserOption );

scanf()需要变量的地址作为参数。 因此,您需要编写:

scanf( "%d",&UserOption );

这就是为什么您收到错误消息的原因。它需要一个指向整数的指针(以便从scanf()内修改UserOption的值),但是您将UserOption传递给scanf()。您正在做的事情称为传递值,但是scanf()需要一个传递参考。由于您是C语言的新手,因此对这两种原理进行了简要说明:

价值传递: 您正在调用的函数会收到您传递的参数的副本。

int foo(int bar){
  ...
}

int main(void){
  int x = 5;
  foo(x);
  ...
  return 0;
}

调用foo()时,会将变量x的副本传递给foo。这意味着功能变量栏将使用x的内容(因此为5)进行初始化。

通过引用: 您正在调用的函数将接收变量的地址。指针用于在C中保存地址。因此,在函数定义栏中,未将其声明为指向int(int *)的指针,并使用x(&x)的地址进行调用。

int foo(int* bar){
  ...
}

int main(void){
  int x = 5;
  foo(&x);
  ...
  return 0;
}

调用foo()时,会将变量x地址的副本传递给foo。这意味着功能指针栏使用x的地址初始化。 bar的内容现在是一个地址。引用传递用于从函数访问非函数变量。由于不需要制作参数的专用副本,因此它还可以提高性能。