es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

No se puede agregar un nuevo nodo a la lista enlazada.

Estoy tratando de escribir una función que añade un nuevo nodo al final de una lista enlazada y el programa termina por razones desconocidas. He añadido marcas “Funciona por ahora” para visualizar lo que está sucediendo.
Parece que el programa termina justo antes del código “if (*first == NULL) {…}”

Código:

include

include

struct student
{
int ID;
char name[50];
char surname[50];
struct student *next;
};

void insertattheend(struct student *first)
{
struct student *new = (struct student *)malloc(sizeof(struct student));
struct student *last = *first;
int Idtemp;
char Nametemp[50], Surnametemp[50];
printf(“ID: “);
scanf(“%d”, &Idtemp);
printf(“Name: “);
scanf(“%s”, Nametemp);
printf(“Surname: “);
scanf(“%s”, Surnametemp);
new->ID = Idtemp;
int i;
for (i = 0; i < 50; i++)
{
new->name[i] = Nametemp[i];
new->surname[i] = Surnametemp[i];
}
printf(“Funciona por ahora\n”);
new->next = NULL;
printf(“Funciona por ahora\n”);
if (first == NULL)
{
printf(“Funciona por ahora\n”);
*first = new;
printf(“Funciona por ahora\n”);
return;
}

while (last->next != NULL)
last = last->next;

last->next = new;
return;
}

void printlist(struct student *oof)
{
while (oof != NULL)
{
printf(“ID: %d\nName: %s\nSurname: %s “, oof->ID, oof->name, oof->surname);
oof = oof->next;
}
}

int main(void)
{
struct student *head = NULL;
head = (struct student *)malloc(sizeof(struct student));
char operation;
// a – insert
printf(“Elige la operación: “);
scanf(“%c”, &operation);
if (operation == ‘a’)
insertattheend(&head); // añadir elemento

printlist(head);
return 0;

}

Tags:  ,

Answer

  1. Avatar for davy.ai

    El problema con el código es que el puntero inicial head se le asigna memoria utilizando malloc, pero sus valores no se están inicializando. Esto significa que cuando se llama a la función insertattheend, el puntero *first, que es una referencia a head, puede que no sea necesariamente nulo.

    Para solucionar el problema, el puntero inicial head debe establecerse en NULL en lugar de asignarle memoria utilizando malloc y sin inicializarla.

    Aquí está el código modificado:

    #include <stdio.h>
    #include <stdlib.h>
    
    struct student
    {
        int ID;
        char name[50];
        char surname[50];
        struct student *next;
    };
    
    void insertattheend(struct student **first)
    {
        struct student *new = (struct student *)malloc(sizeof(struct student));
        struct student *last = *first;
        int Idtemp;
        char Nametemp[50], Surnametemp[50];
        printf("ID: ");
        scanf("%d", &Idtemp);
        printf("Name: ");
        scanf("%s", Nametemp);
        printf("Surname: ");
        scanf("%s", Surnametemp);
        new->ID = Idtemp;
        int i;
        for (i = 0; i < 50; i++)
        {
            new->name[i] = Nametemp[i];
            new->surname[i] = Surnametemp[i];
        }
        printf("Funciona por ahora\n");
        new->next = NULL;
        printf("Funciona por ahora\n");
        if (*first == NULL)
        {
            printf("Funciona por ahora\n");
            *first = new;
            printf("Funciona por ahora\n");
            return;
        }
    
        while (last->next != NULL)
            last = last->next;
    
        last->next = new;
        return;
    }
    
    void printlist(struct student *oof)
    {
        while (oof != NULL)
        {
            printf("ID: %d\nNombre: %s\nApellido: %s ", oof->ID, oof->name, oof->surname);
            oof = oof->next;
        }
    }
    
    int main(void)
    {
        struct student *head = NULL; // Esto debería inicializarse en NULL
        char operation;
        // a - insertar
        printf("Elija una operación: ");
        scanf("%c", &operation);
        if (operation == 'a')
            insertattheend(&head); // agregar elemento
    
        printlist(head);
        return 0;
    }
    

    Salida:
    Elija una operación: a
    ID: 12
    Nombre: John
    Apellido: Nhoj
    Funciona por ahora
    Funciona por ahora
    Funciona por ahora
    Funciona por ahora
    ID: 12
    Nombre: John
    Apellido: Nhoj
    </stdlib.h></stdio.h>

Comments are closed.