/* Some dynamic allocation of structures */ #include #include #include int main() { struct datalist { char name[20]; struct datalist *next; }; struct datalist *head, *current, *new; int i; /* set up an initial list */ head = (struct datalist *)malloc(sizeof(struct datalist)); sprintf(head->name, "The number %d", 0); current = head; for (i=1; i<10; i++) { new = (struct datalist *)malloc(sizeof(struct datalist)); sprintf(new->name, "The number %d", i); current->next = new; new->next = NULL; current = new; } /* print out the list */ printf("The initial list is:\n"); current = head; while (current->next != NULL) { printf("%s\n", current->name); current = current->next; } /* now let's make a new entry */ new = (struct datalist *)malloc(sizeof(struct datalist)); sprintf(new->name, "Hi There!"); /* find a spot to insert it */ current = head; for (i=0; i<3; i++) current = current->next; /* insert the new entry at this point */ new->next = current->next; current->next = new; /* and print 'em out again */ printf("\n\nThe new list:\n"); current = head; while (current->next != NULL) { printf("%s\n", current->name); current = current->next; } /* finally, let's delete an item from the list */ current = head; for (i=0; i<3; i++) current = current->next; /* set new to point to the item after current */ new = current->next; /* now repoint current's next pointer to the item after new */ current->next = new->next; /* now that it's out of the linked list, we'll free the memory used by the now-unused list item */ free(new); /* finally, print the list out once again */ printf("\n\nThe list with item deleted is:\n"); current = head; while (current-> next != NULL) { printf("%s\n", current->name); current = current->next; } }