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;
}
davy.ai
El problema con el código es que el puntero inicial
head
se le asigna memoria utilizandomalloc
, pero sus valores no se están inicializando. Esto significa que cuando se llama a la funcióninsertattheend
, el puntero*first
, que es una referencia ahead
, puede que no sea necesariamente nulo.Para solucionar el problema, el puntero inicial
head
debe establecerse enNULL
en lugar de asignarle memoria utilizandomalloc
y sin inicializarla.Aquí está el código modificado:
Salida:
Elija una operación: a
</stdlib.h></stdio.h>ID: 12
Nombre: John
Apellido: Nhoj
Funciona por ahora
Funciona por ahora
Funciona por ahora
Funciona por ahora
ID: 12
Nombre: John
Apellido: Nhoj