首页 > 解决方案 > 如何在c中将字符串添加到链表?

问题描述

我已经知道如何将 int 添加到 C 中的链表中,但我需要添加一个字符串,但它根本不起作用。

主函数从用户那里获取数据,添加到链表后在show函数中打印出来。

列表和主要

struct nlista{
    char dado[10];
    struct nlista *prox;
}*Head;

int main(){
    int op;
    char data[10];
    Head = NULL;

    printf("type a value: ");
    scanf("%s",&data);
    inserir(data);
    printf("the element is : ");
    show();
}

inserir():将元素添加到列表末尾

    void inserir(char data){

    nlista *novoelemento;
    novoelemento = (struct nlista *)malloc(sizeof(struct nlista));
    nlista *check;
    check = (struct nlista *)malloc(sizeof(struct nlista));

    novoelemento->dado = data;

    if(Head == NULL){
        Head = novoelemento;
        Head->prox = NULL;
    }
    else{
        check = Head;
        while(check->prox != NULL)
            check = check->prox;

        check->prox = novoelemento;
        novoelemento->prox = NULL;  
    }

show():显示链表

    void show()
{
    nlista *check;
    check = (struct nlista *)malloc(sizeof(struct nlista));

    check = Head;
    if (check == NULL){
        return;
    }

    while(check != NULL) {
        printf("%s", check->dado);
        check=check->prox;
    }
    printf("\n");
}

我错过了什么?编译器消息是:从 char* 到 char 的无效转换。在 inserir(data) 行中;

标签: cstringdata-structureslinked-list

解决方案


我们有char dado[10];,但novoelemento->dado = data;正如您所发现的,这不会编译。

您似乎希望strncpy(novoelemento->dado, data, 10)[9] = 0;这将数据中的字符串复制过来并确保它正确地以空值终止。

如果你有strlcpy,你可以做得更好strlcpy(novoelemento->dado, data, 10);


推荐阅读