C语言。如何将字符串添加到链接列表中

标签 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[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.

有时我会遇到段错误,有时它根本不起作用。我必须使用 strcpy(a,b) 来复制字符串吗?

最佳答案

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);

关于C语言。如何将字符串添加到链接列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16092046/

相关文章:

ios - 正确检查 Objective-C 中是否存在 C 函数

cat 会破坏程序,手动 stdin 输入不会

CS50 集成开发环境 : printf returns extra characters

pointers - [Golang]指针类型、指针类型和结构体类型调用方法有什么不同?

C++ 指向函数的指针

c - STM8 ASM 安全执行 WFE

c - Flatindexed 2D array - 垂直/水平翻转图像

c# - LINQ.Any 到字符串的结果

从包含 R 中特定字符的字符串向量中删除条目

c++ - nullptr 是否用于终止 C 风格的字符串?