Buongiorno a tutti!
Sto studiando tutta la parte sulla memoria dinamica e c'è questo programma già svolto che non riesco a capire:
[CODE]
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
typedef struct Elem
{
char *info;
struct Elem *next;
} Elem;
Elem * estrai(Elem **h, char *nome);
void stampa (Elem *h);
void *myAlloc (int dim);
int
main (void)
{
Elem *h, *a;
char nome[20];
h = NULL;
printf ("Inserire un nome (EOF per finire) => ");
while (scanf ("%s", nome) != EOF) {
a = (Elem *) myAlloc (sizeof (Elem));
a->info = strdup (nome);
a->next = h;
h = a;
printf ("Inserire un altro nome (EOF per finire) => ");
}
while (1) {
printf ("Inserire un nome: ");
scanf ("%s", nome);
a = estrai(&h, nome);
if (a){
printf ("Nome %s \n", a->info);
free(a);
}
else
printf ("Nome %s non trovato\n", nome);
stampa(h);
}
system("pause");
}
Elem * estrai(Elem **h, char *nome){
Elem *p, *a;
p = NULL;
a = *h;
while (a && strcmp (a->info, nome)) {
p = a;
a = a->next;
}
if (a) {
if (p)
p->next = a->next;
else
*h = a->next;
}
return a;
}
void stampa (Elem *h){
Elem *a;
a = h;
while (a) {
printf ("%s ", a->info);
a = a->next;
}
printf ("\n");
}
void *
myAlloc (int dim) {
void *p;
p = malloc(dim);
if (p == NULL) {
fprintf (stderr, "ERRORE: memoria dinamica insufficiente.\n");
exit (1);
}
return p;
}
[\CODE]
Non capisco:
- la funzione strdup cosa fa di preciso;
- nella riga 32 cosa vuol dire while (1)
- quando scrivo i nomi e poi metto ctrl z il programma non continua a fare più nulla
quindi non capisco quale sia il compito di questo programma.
Vi rigrazio per l'aiuto