gpt4 book ai didi

c - 从类型 'char[50]' 分配给类型 'char *' 时,类型不兼容

转载 作者:行者123 更新时间:2023-11-30 15:19:28 24 4
gpt4 key购买 nike

我正在尝试创建一个链接列表。我有一个函数可以从我的链接列表中删除(删除函数)内容。但当我尝试比较字符串时,它似乎崩溃了。它一直工作到最后一个随机 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 有关。但是有人有什么想法吗?

最佳答案

主要问题是:

void delete(char delName)

应该是这样的:

void delete(char *delName)

但是,您的程序还存在许多其他问题,需要很长时间才能将它们全部列出。我只给你两个需要解决的问题:

  1. 您应该打开警告并修复所有警告。

  2. 您的函数不应调用 main()。相反,main() 应该包含一个循环,如下所示:

    //create the portion that decides the user input
    int userSelection = 0 ;
    do {
    scanf("%d", &userSelection);
    userSelect(userSelection);
    } while (userSelection != 5);

关于c - 从类型 'char[50]' 分配给类型 'char *' 时,类型不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30629931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com