【问题标题】:change the value of a string in a linked list更改链表中字符串的值
【发布时间】:2020-08-12 00:01:33
【问题描述】:

我是 C 的初学者,希望有人能帮助我。所以,我一直在尝试将字符串名称的值更改为另一个值,但是当打印列表时,当我使用scanf 输入值时,字符串的值不会改变。例如,如果我像这样使用函数push(&head, "Carlos") 手动插入值,则名称的值会发生变化。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Node{
    char *name;
    struct Node *next;
};


void printList(struct Node *n){
    while (n != NULL){
        printf(" name: %s \n ", n->name);
        printf("....................................\n");
        n = n->next;
    }
}

void push(struct Node **head_ref,  char *name){
    struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
    new_node->name = name;

    new_node->next = (*head_ref);

    (*head_ref) = new_node;
}

int main(){
    struct Node *head = NULL;

    char name[20];

    printf("Insert a name");
    scanf("%s", name);

    push(&head, name);

    printf("Insert a new name");
    scanf("%s", name);

    push(&head, name);

    push(&head, "Carlos");


    printList(head);

    return 0;
}

如果我输入两个这样的名称:“nadia”、“pedro”,输出将是这样的:

    Output:

    Carlos
    ....................................
    pedro
    ....................................
    pedro
    ....................................

我想要的结果是这样的:

    Output:

    Carlos
    ....................................
    pedro
    ....................................
    nadia
    ....................................

【问题讨论】:

    标签: c string linked-list


    【解决方案1】:

    你是从用户到scanf名字的同一个缓冲区!您需要为下一个 scanf 分配(在堆上或堆栈上)另一个缓冲区。
    见主要:

       int main(){
        struct Node *head = NULL;
        char namex[20];
        char namey[20];
        printf("Insert a name\n");
        scanf("%s", namex);
        push(&head, namex);
        printf("Insert a new name\n");
        scanf("%s", namey);
        push(&head, namey);
        printList(head);
    
       return 0;
    }
    

    【讨论】:

    • 谢谢你,我的朋友!我不知道我必须重新分配一个新的价值,这是我的一个新概念
    【解决方案2】:

    您应该使用strcpy 在c 中复制字符串。您必须在每个new_node 中为name 分配:

    new_node->name = malloc(20*sizeof(char));
    if(!new_node->name) {//handle error}
    strcpy(new_node->name,name);
    

    我在你的代码中看到:

     scanf("%s", name);
    

    你应该改成(你可以看到Disadvantages of scanf):

     scanf("%19s", name);
    

    或者您可以使用fgets 代替:

    fgets(name, sizeof(name), stdin);
    

    【讨论】:

    • 非常感谢你,仁!我想如果我想添加一个姓氏字符串,我应该复制该字符串并为姓氏分配
    • yub。当你使用strcpy(destination, source)时,如果destination是一个字符指针,你必须在复制前为其分配。
    猜你喜欢
    • 2018-10-07
    • 2014-11-05
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多