C语言链表字符串搜索问题:电话目录按姓名号码查询并展示条目
C语言链表电话目录搜索功能问题修复
现存问题汇总
- 字符串比较逻辑错误:C语言中直接用
==比较字符串,对比的是两个字符串的内存地址而非内容,必须调用<string.h>头文件中的strcmp()函数判断字符串是否相等,返回0表示内容一致。 - 输入变量未分配有效内存:搜索函数中的
char *f是未初始化的野指针,没有开辟内存空间存储输入的姓名,会导致内存访问异常,应该定义为长度足够的字符数组char f[32]。 - 结构体成员类型定义错误:
number定义为int*指针类型完全没有必要,直接定义为int即可存储整数号码,现有写法下直接向指针地址写入int值会触发内存错误。 - 搜索逻辑流程错误:
searchByFirstName将用户输入逻辑写在遍历链表的while循环内部,会出现每遍历一个节点就要求用户输入一次姓名的问题,输入逻辑应该移到循环外。searchByLastName、searchByNumber没有遍历全链表,只判断了第一个节点就结束,匹配不到后续节点的内容。
- 输入函数参数错误:数组名本身就是首地址,
scanf("%s", &nn->firstname)中的&多余,直接写nn->firstname即可。
修复后完整代码
#include <stdio.h> #include <stdlib.h> #include <string.h> // 修正结构体成员类型 struct node { char firstname[32]; char lastname[32]; int number; struct node *next; }*head; struct node *start=NULL; struct node *getnode() { return (struct node *)malloc(sizeof(struct node)); } // 展示单个匹配条目的完整信息 void displayNode(struct node *n) { printf("\n===== 匹配条目 =====\n"); printf("名:%s\n", n->firstname); printf("姓:%s\n", n->lastname); printf("号码:%d\n", n->number); printf("====================\n"); } void display(struct node *start) { struct node *temp = start; printf("\n===== 电话目录 =====\n"); while(temp != NULL) { printf("名:%s,姓:%s,号码:%d\n", temp->firstname, temp->lastname, temp->number); temp = temp->next; } printf("====================\n"); } void insert() { struct node *temp,*nn; nn=getnode(); temp=start; while(temp->next!=NULL) { temp=temp->next; } printf("Enter First name:\n"); scanf("%s", nn->firstname); printf("Enter Last name:\n"); scanf("%s", nn->lastname); printf("Enter number:\n"); scanf("%d", &nn->number); temp->next=nn; nn->next=NULL; display(start); } void create() { struct node *nn; if(start!=NULL) insert(); else { nn=getnode(); start=nn; printf("Enter First name:\n"); scanf("%s", nn->firstname); printf("Enter Last name:\n"); scanf("%s", nn->lastname); printf("Enter number:\n"); scanf("%d", &nn->number); nn->next=NULL; display(start); } } void searchByFirstName() { char f[32]; struct node* temp = start; int found = 0; // 输入逻辑移到循环外 printf("Enter First Name to be searched:\n"); scanf("%s", f); while (temp != NULL){ // 调用strcmp比较字符串内容 if (strcmp(temp->firstname, f) == 0){ printf("\n Record Found!\n"); displayNode(temp); found = 1; } temp = temp->next; } if(!found) { printf("\n Record not found\n"); } } void searchByLastName() { char f[32]; struct node* temp = start; int found = 0; printf("Enter Last Name to be searched:\n"); scanf("%s", f); // 新增全链表遍历逻辑 while (temp != NULL){ if (strcmp(temp->lastname, f) == 0){ printf("\n Record Found!\n"); displayNode(temp); found = 1; } temp = temp->next; } if(!found) { printf("\n Record not found\n"); } } void searchByNumber() { int l; struct node* temp = start; int found = 0; printf("Enter Number to be searched:\n"); scanf("%d", &l); while (temp != NULL){ if (temp->number == l){ printf("\n Record Found!\n"); displayNode(temp); found = 1; } temp = temp->next; } if(!found) { printf("\n Record not found\n"); } }
内容的提问来源于stack exchange,提问作者Luke Grech
相关产品推荐
相关产品推荐

