C语言。如何向链表中添加字符串
由于某种原因,我不能让它工作。这是我在代码中的函数,如果这还不足以帮助我,我将很高兴地发布整个代码C语言。如何向链表中添加字符串,c,string,pointers,linked-list,C,String,Pointers,Linked List,由于某种原因,我不能让它工作。这是我在代码中的函数,如果这还不足以帮助我,我将很高兴地发布整个代码 char addcity() { citylist=malloc(sizeof(struct city)); struct city *temp; char addcity[50]; char addstate[50]; char addpopulation[50]; char addregion[50]; char addzipcode[5
char addcity()
{
citylist=malloc(sizeof(struct city));
struct city *temp;
char addcity[50];
char addstate[50];
char addpopulation[50];
char addregion[50];
char addzipcode[50];
//temp = citylist;
//citylist=malloc(sizeof(struct city));
//struct city *ptr=citylist;
struct city *ptr= (struct city*)malloc(sizeof(struct city));
printf("Which city would you like to add?: ");
scanf("%s",addcity);
printf("Which state is the city in?: ");
scanf("%s",addstate);
printf("What is the population?: ");
scanf("%s", addpopulation);
printf("what is the region?: ");
scanf("%s", addregion);
printf("what is the zipcode?: ");
scanf("%s", addzipcode);
int found;
ptr->name=addcity;
ptr->statecode=addstate;
ptr->population=addpopulation;
ptr->region=addregion;
ptr->zipcode=addzipcode;
ptr->next=NULL;
curr->next=ptr;
curr=ptr;
printlist(); //this just prints out the whole list.
有时我会出现分割错误,而有时根本不起作用。我是否必须使用strcpya,b来复制字符串。您的代码中有一些问题。第一个问题是在结构中设置指针指向局部变量。一旦代码离开addcity,这些局部变量将不再有效,任何试图使用它们的人都会遇到麻烦
要将本地字符串复制到您的结构中,您需要使用某种形式的字符串复制函数,如strcpya,b.请不要张贴大量未注释的代码,并要求我们为您调试。设身处地为我们着想——你能帮助问这样问题的人吗?请证明您自己至少已经做了基本的调试工作。给我们调试器、程序等的输出。最后,给我们一段代码,我们可以自行编译以重现错误。否则,我们无法知道bug不在其他地方。也许您需要阅读有关在调试器中单步执行此操作的指针,这可能会有所帮助。此外,理解指针和C范围也会有所帮助。
printf("Enter String ::");
scanf("%s",&ptr->str);
printf("Which city would you like to add?: ");
scanf("%s",&ptr->name);
printf("Which state is the city in?: ");
scanf("%s",&ptr->statecode);
printf("What is the population?: ");
scanf("%s",&ptr->population);
printf("what is the region?: ");
scanf("%s",&ptr->region);
printf("what is the zipcode?: ");
scanf("%s",&ptr->zipcode);