【发布时间】:2019-12-26 16:51:39
【问题描述】:
我正在使用单链表在 c 中创建一个电话簿系统,似乎一切正常,但删除选项总是给我一个错误,我不知道如何修复它,所以我希望有人能告诉我是什么代码中的问题,给我看一个可以修改此代码中名称或数字的代码
#include<stdio.h>
#include<stdlib.h>
struct node
{
char firstname[20];
char lastname[20];
long int number;
struct node *next;
};
struct node *head=NULL;
struct node *getnode()
{
return((struct node *)malloc(sizeof(struct node)));
}
void display(struct node *head)
{
struct node *temp;
temp=head;
while(temp!=NULL)
{
printf("%s\n",temp->firstname);
printf("%s\n",temp->lastname);
printf("%d\n",temp->number);
temp=temp->next;
}
}
void insert()
{
struct node *temp,*newnode;
newnode=getnode();
temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
}
printf("Enter First name:\n");
scanf("%s",&newnode->firstname);
printf("Enter Last name:\n");
scanf("%s",&newnode->lastname);
printf("Enter number:\n");
scanf("%d",&newnode->number);
temp->next=newnode;
newnode->next=NULL;
display(head);
}
struct node *create()
{
struct node *temp,*newnode;
if(head!=NULL)
insert();
else
{
newnode=getnode();
head=newnode;
temp=head;
printf("Enter First name:\n");
scanf("%s",&newnode->firstname);
printf("Enter Last name:\n");
scanf("%s",&newnode->lastname);
printf("Enter number:\n");
scanf("%d",&newnode->number);
newnode->next=NULL;
display(head);
}
}
void search()
{
struct node *temp;
char *first,*last;
temp=head;
printf("Enter name to be searched:\n");
scanf("%s",&first);
scanf("%s",&last);
while((temp->firstname==first)&&(temp->lastname==last))
{
temp=temp->next;
}
printf("%s\n",temp->firstname);
printf("%s\n",temp->lastname);
printf("%d\n",temp->number);
}
void del()
{
struct node *pretemp,*temp;
char *f,*l;
temp=head;
pretemp=head->next;
printf("Enter name :");
scanf("%s",&f);
scanf("%s",&l);
while(temp!=NULL){
if((pretemp->firstname==f)&&(pretemp->lastname==l))
{
printf("%s ",temp->firstname);
printf("%s ",temp->lastname);
printf("%s ",temp->number);
temp=pretemp->next;
delete pretemp;
break;
}
else
{
temp=temp->next;
pretemp=pretemp->next;
}
}
int main()
{
int op,ch;
do{
printf("-------Welcome--------\n");
printf("1.Create\n2.Display\n3.Delete\n4.Search\n");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: create();
break;
case 2: display(head);
break;
case 3: del();
break;
case 4:search();
break;
}
printf("Do you want to quit ? 1 for no / 0 for yes:");
scanf("%d",&op);
}while(op);
return 0;
}
【问题讨论】:
-
请分享错误信息
-
delete pretemp; -
尝试附加调试器,这可能有助于您确定错误情况
-
您的代码似乎无法编译。无论如何,现在是学习如何调试程序的好时机。看看这里 - stackoverflow.com/questions/2590931/how-to-debug-a-c-program 您很可能由于缓冲区溢出或错误指针而访问无效内存。请编辑源代码并提供实际编译的minimal reproducible example。
-
如果您正在编写
delete pretemp;,那么您是在使用 C++ 而非 C 进行编码。但是(显然)您正在使用malloc(在struct node *getnode中)分配内存。您不应该混合 C(malloc/free)和 C++(new/delete)内存分配。我建议您选择其中一个。
标签: c data-structures