String changing previous list names (Struct + String + Function)

Asked

Viewed 33 times

-2

Good afternoon, I was giving a study in lists and I went to do a little programming but I can’t at all pass my string in the correct way to the function so that it doesn’t change all my previous names from my list, I tried some modifications on pointers but always keeps changing the previous names of the list.

The only way I could was using strcpy, but I wanted to know how to do without using it, I thank you from now on!

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

struct pessoa
{
    char *nome;
    int rg;
    struct pessoa *proximo;
};

void imprimeMenu();
void imprimeEncadeada(struct pessoa *ponteiroEncadeada);
struct pessoa *addInicioEncadeada(struct pessoa *ponteiroEncadeada, char *nome, int rg);

int main(){

    struct pessoa *ponteiroEncadeada = malloc(sizeof(struct pessoa));
    ponteiroEncadeada->nome = "";
    ponteiroEncadeada->rg = 0;
    ponteiroEncadeada->proximo = NULL;

    char *nome = (char *) malloc(50 * sizeof(char));
    int opEscolhida = 1, rg, pos;

    while (opEscolhida < 10 && opEscolhida > 0)
    {
        imprimeMenu();
        printf ("\nEscolha o numero da operacao e aperte ENTER: ");
        scanf(" %d", &opEscolhida);

        switch (opEscolhida)
        {
            case 1:
                printf("Digite um nome: ");
                scanf(" %s", nome);
                printf("Coloque o RG: ");
                scanf(" %d", &rg);
                printf("\n");

                ponteiroEncadeada = addInicioEncadeada(ponteiroEncadeada, nome, rg);
                break;

            case 2:
                break;
        }
        imprimeEncadeada(ponteiroEncadeada);
    }
    free(ponteiroEncadeada);
}

void imprimeMenu()
{
    printf ("\n\nOperacoes: \n");
    printf ("1 - Insercao de um node no inicio da lista \n");
}

void imprimeEncadeada(struct pessoa *ponteiroEncadeada){

    int i = 1;

    struct pessoa *listaEncadeada = ponteiroEncadeada;

    while (listaEncadeada != NULL){
        printf("%02d - Nome: %s || RG: %d\n", i, listaEncadeada->nome, listaEncadeada->rg);
        listaEncadeada = listaEncadeada->proximo;
        i++;
    }
}

struct pessoa *addInicioEncadeada(struct pessoa *listaEncadeada, char *nome, int rg){

    struct pessoa *novoValor = malloc(sizeof(struct pessoa));

    novoValor->nome = nome;
    novoValor->rg = rg;
    novoValor->proximo = listaEncadeada;

    listaEncadeada = novoValor;

    return listaEncadeada;
}


1 answer

0

Without strcpy you will have to loop and store letter by letter:

for (int i = 0; i < nome.length; i++) 
    novoValor->nome[i] = nome[i];

However, for this method to work, you cannot use the name variable in your struct as a pointer.

Browser other questions tagged

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