c - How to search in a queue?
问题描述
Suppose if I enter 5 passenger's details I'm only able to retrieve the first passenger's details even if I search for the 4th passenger's details.I need to find any element in the list.If current= frontq; it's showing first element when searched.
CODE:
int search()
{ struct bag *next;
char *n,*f;
current=frontq;
printf("Enter name to be searched:\n");
scanf("%s",&n);
printf("\nEnter the flight number\n");
scanf("%s",&f);
while((current->name==n)&&(current->fl_no==f))
{
current=current->next;
next++;
}
printf ("\n The Searched luggage is\n");
printf("%s\n",current->name);
printf("%s\n",current->dest);
printf("%s\n",current->fl_no);
return 0;
}
解决方案
对于初学者,这些指针
char *n,*f;
未初始化并且具有不确定的值。
而这些 scanf 的调用
scanf("%s",&n);
scanf("%s",&f);
使用不正确的参数并因此调用未定义的行为。
您需要声明适当大小的数组,例如
char n[N], f[N];
其中 N 是一些值,至少在 scanf 调用中写入
scanf( "%s", n);
scanf( "%s", f);
同样在写入错误比较指针的while循环的情况下
while((current->name==n)&&(current->fl_no==f))
你应该写
while( current != NULL &&
!( strcmp( current->name, n ) == 0 && strcmp( current->fl_no, f ) == 0 ) )
在循环之后你应该写
if ( current != NULL )
{
printf ("\n The Searched luggage is\n");
printf("%s\n",current->name);
printf("%s\n",current->dest);
printf("%s\n",current->fl_no);
}
函数的返回值也没有意义。最好把返回表达式写成
return current != NULL;
在这种情况下,函数的用户可以检查是否找到了所需的队列元素。
推荐阅读
- .htaccess - 在 htaccess 中强制使用 HTTPS,同时仅使公用文件夹可访问
- javascript - Javascript Dsiplay 2 个字符串在一个警报中
- excel - 如何在运行 VBA 的情况下更新 API 库存值
- java - 如何识别导致代码失败的边缘案例?
- php - 如何在注册过程中检查用户是否输入了字母数字
- flutter - Flutter 创建一个凸起的按钮
- reactjs - 您能否将脚本注入到 React 页面(使用 Draft.js 编辑器)以将 HTML 附加到编辑器的现有内容?
- azure-cosmosdb - 嵌套对象子级的 Cosmos DB SQL API 查询
- android - 工具栏隐藏其他元素 android kotlin
- xaml - 按钮在较低分辨率下转义堆栈布局