【发布时间】:2015-06-03 20:22:35
【问题描述】:
我正在尝试创建一个链接列表。我有一个从我的链接列表中删除(删除函数)内容的函数。但是当我尝试比较字符串时它似乎崩溃了。它一直工作到最后一个随机 printf 语句。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
char data[50];
struct node *next;
}*head;
int main()
{
//creates a sudo user interface
printf("1. Insert\n");
printf("2. Display\n");
printf("3 Count\n");
printf("4. Delete\n");
printf("5. Exit\n");
//create the portion that decides the user input
int userSelection = 0 ;
scanf("%d", &userSelection);
userSelect(userSelection);
return 0;
}
//this function will handle user imput
void userSelect(int num)
{
if(num == 1)
{
printf("What is your name?\n");
char userName[30];
scanf(" %s", userName);
add(userName);
} else if(num ==2) {
display();
} else if (num ==2){
//do something
} else if (num ==3){
printf("%d", count());
main();
} else if (num ==4 ){
char delName[50];
printf("Who do you want to remove?\n");
scanf("%s", delName);
delete(delName);
}else if (num == 5){
// return 0;
}else if (num > 6){
printf("\n52Please make sure you use a valid option!\n\n");
main();
}
}
void add( char userName[] )
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
strcpy(temp->data, userName);
if (head== NULL)
{
head=temp;
head->next=NULL;
}
else
{
temp->next=head;
head=temp;
}
printf("\n");
main();
}
int count()
{
struct node *n;
int c=0;
n=head;
while(n!=NULL)
{
n=n->next;
c++;
}
printf("\n");
return c;
}
void display(struct node *r)
{
r=head;
if(r==NULL)
{
return;
}
while(r!=NULL)
{
printf("%s ",r->data);
r=r->next;
}
printf("\n");
main();
}
void delete(char delName)
{
struct node *temp, *prev;
temp=head;
printf("sffs\n");
while(temp!=NULL)
{
printf("sdg\n");
if(strcmp(temp->data, delName)==0)
{
if(temp==head)
{
head=temp->next;
free(temp);
return 1;
}
else
{
prev->next=temp->next;
free(temp);
return 1;
}
}
else
{
prev=temp;
temp= temp->next;
}
}
main();
}
我认为这与删除函数中的strcmp有关..但是有人有什么想法吗?
【问题讨论】:
-
您应该发布其余的代码。你有一个
free,我们看不到它被分配到哪里。另外,你打电话给main吗?这不可能…… -
delName真的是char还是char *?你应该编译所有警告(gcc -Wall,如果你使用 gcc)。 -
我调用 main 只是为了在用户完成任务后再次使用菜单,它会返回并再次提示他们。
-
我将 delName 设为一个指针,它不会崩溃。现在我不能让它调用 main 并重新打开菜单,所以我可以检查它是否真的被删除了:O
-
你是从
delete()打电话给main()???