arrays - 使用结构化编程实现队列
问题描述
我是 C 新手,所以我们的课程从使用结构化编程开始。就参数 # 而言,一切都很好,但我很难理解错误消息。当尝试调用 enqueue 和 dequeue 时,它说 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 新手,因此这里对这两个原则进行快速解释:
Pass-by-Value: 您正在调用的函数接收您传递的参数的副本。
int foo(int bar){
...
}
int main(void){
int x = 5;
foo(x);
...
return 0;
}
当调用 foo() 时,变量 x 的副本被传递给 foo。这意味着函数变量 bar 使用 x 的内容进行初始化,因此为 5。
Pass-by-reference:您正在调用的函数接收变量的地址。指针用于在 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 的内容现在是一个地址。引用传递用于通过函数访问非函数变量。它还可以提高性能,因为您不需要制作参数的专用副本。
推荐阅读
- python - discord.py 将上下文和自我传递给类中的函数
- jsp - How to resolve this issue? Failed to Compile JSP: This attribute is not recognized
- android - Android Studio 布局编辑器设计视图卡在初始化
- javascript - 当需要填写表格时,如何禁用弹出成功消息?
- java - java中当两个日期之间的天数差大于某个值时删除记录
- sql - 在 SQL 中单行显示多列
- r - 根据分类变量 (geom_area) 更改曲线下区域的颜色
- node.js - 将 Node.js Docker 从本地(Apple M1)推送到 Heroku 时继续遇到相同的部署错误(Exec Format Error)
- php - laravel 雄辩模型无法存储十进制值
- symfony - 在 Symfony 4.4 中覆盖复选框表单字段产生重复标签且没有字段