Printf does not print within the while

2

The purpose of the code is to print the values from linked lists.   Example of how the list is:
   L-> [3] -> [4] -> [5] -> X, should print 3, 4, 5. However it does not.

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;
}
    
asked by anonymous 24.04.2018 / 13:03

3 answers

1

The other answers already indicate the biggest problem you have, which is not to use what is returned in the insereL function to bind the list, however, there is still another problem that is using the LInt without initialization:

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

What will potentially give you a segmentation fault in the print part, because the list will not end in NULL as you would expect.

To fix both of these 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 Ideone how it works with these elevations

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

  • All other variables you have are written in Portuguese, so this should be too, 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 for C ++ but it makes reading difficult for anyone who understands c ++.

24.04.2018 / 14:36
0

Your code does not modify the Lint variable it receives as the first parameter, you create a new element and it returns but this is not stored and so when the list is empty it is printed.

    
24.04.2018 / 13:19
0

The insert function does not connect the created objects, that is, when at the time of printing you "walk" between the objects

l = l -> prox;

is not pointing to objects instantiated in insert function.

    
24.04.2018 / 13:19