Copy string to struct

Asked

Viewed 805 times

-1

While trying to copy String nome into String in Struct novo->nome the program stops working if I comment on the function strcpy(novo->nome,nome); the code is executed normally.

//Função de inserção:
lista *insere_lista(lista *l,char *nome,int idade){
    lista *novo = (lista *)malloc(sizeof(lista));

    strcpy(novo->nome,nome);
    novo->idade = idade;
    novo->proximo = l;
    return novo;
}

//Main:
int main(){
    int opc,idade;
    char *nome;

    lista *l;
    l = cria_lista();

    do{
        printf("\n1 - Inserir\n");
        printf("2 - Retirar\n");
        printf("3 - Mostrar\n");
        printf("4 - Busca\n");
        printf("0 - Sair\n");
        scanf("%d",&opc);

        if(opc == 1){
            printf("Digite o nome:");
            fflush(stdin);
            scanf("%s",&nome);
            printf("Digite a idade:");
            fflush(stdin);
            scanf("%d",&idade);

            l = insere_lista(l,nome,idade);
        }

        if(opc == 3){
            mostra_lista(l);
        }

    }while(opc!=0);
}

//Struct:
typedef struct lista{
    char *nome;
    int idade;
    struct lista *proximo;
}lista;

Imagem do Erro

  • What error are you receiving? Try to clarify the question (https://answall.com/questions/228373/copiar-string-para-struct).

  • nome is already a pointer, so to do the scanf I was trying to do would have to be scanf("%s",nome); without the &. It is not advisable to forget that the scanf receives the memory address where will put the read data

1 answer

0

I solved the problem by changing scanf("%s",&nome); for gets(nome);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.