使用结构化编程实现队列

Implementing a Queue using Structured programming

我是 C 的新手,所以我们的 class 从使用结构化编程开始。就参数 # 而言,一切都很好,但我很难理解错误消息。当尝试调用 enqueue 和 dequeue 时,它​​说 and 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;
    }
}

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

您写道:

scanf( "%d",UserOption );

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

scanf( "%d",&UserOption );

这就是您收到错误消息的原因。它需要一个指向整数的指针(以便从 scanf() 中修改 UserOption 的值)但是您将 UserOption 传递给 scanf()。你正在做的事情叫做 Pass-by-Value 但 scanf() 需要一个 Pass-By-Reference。由于您是 C 语言的新手,这里有两个原则的快速解释:

按值传递: 您正在调用的函数接收您传递的参数的副本。

int foo(int bar){
  ...
}

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

当 foo() 被调用时,变量 x 的副本被传递给 foo。这意味着函数变量 bar 是用 x 的内容初始化的,因此是 5.

参考传递: 您正在调用的函数接收变量的地址。指针在C中是用来保存一个地址的。因此在函数定义中bar没有被声明为一个指向int(int*)的指针,而是以x(&x)的地址调用。

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

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

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