Printf does not print inside the while

Asked

Viewed 100 times

2

the purpose of the code is to print the values of linked lists. Example of what the list looks like:
L->[3]->[4]->[5]->X, should print 3, 4, 5. However.

typedef struct lligada {
    int valor;
    struct lligada *prox;
} *LInt;


LInt insereL (LInt l, int x){
    LInt new;
    new = malloc(sizeof(struct lligada));
    new->valor = x;
    new->prox = l;
    //printf("%d\n", new -> valor);
    return new;
}

void imprimeL (LInt l){
    while (l != NULL){
        printf("%d\n", l -> valor);
        l = l -> prox;
    }
}

int main(){
    LInt new;
    insereL(new, 5);
    insereL(new, 4);
    insereL(new, 3);
    imprimeL(new);
    //freeL(new);
    //puts("Hello World!");
    return EXIT_SUCCESS;
}
  • "should print 10, 20, 30" - What do you mean ? In your code, you added the values 5, 4 and 3

  • Isac, these values were supposed to be just an example, but I’ve edited them to better understand.

3 answers

2


The other answers already indicate which is the biggest problem you have, which is not using what is returned in the function insereL in order to connect the list, however, there is still another problem that is using the pointer LInt without being initialized:

LInt new;
insereL(new, 5); //utilizar new sem estar inicializado

What will potentially give you a Segmentation fault on the printing part, as the list will not end in NULL how was supposed.

To fix these two problems you need to change the main:

int main(){
    //iniciar com NULL que serve para o fim da lista, e que joga com a parte da impressão 
    //quando faz while (l != NULL){
    LInt new = NULL; 

    new = insereL(new, 5); //guarda resultado de novo em new, que é a nova cabeça da lista
    new = insereL(new, 4); //guarda neste tambem
    new = insereL(new, 3); //e neste
    imprimeL(new);

    return EXIT_SUCCESS;
}

See in Ideone how it already works with these altearções

There would certainly be other recommendations to make, but I’ll just summarize to one, change the name of the variable new, for the following reasons:

  • All the other variables you have are written in Portuguese, so it should also be written, thus giving more coherence to the code. A reasonable name would be novo, or novo_no.

  • new is a reserved word in c++, this is visible by the special color you see here given to the word. This means that your code is not only not portable to C++ but also makes it difficult to read to those who perceive c++.

0

Your code does not modify the Lint variable you receive as the first parameter, you create a new element and return but this is not stored and so when you print the list is empty.

0

The function inserts does not connect the created objects, ie when at the time of printing you "walk" between the objects

l = l -> prox;

is not pointing to the instantiated objects in the function inserts.

Browser other questions tagged

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