Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <malloc.h>
- struct list {
- char *name;
- char *type;
- int occurance;
- struct list *prev;
- struct list *link;
- };
- struct list *start=NULL,*ptr,*newnode;
- void main() {
- int choice = 0;
- char name1[10], type1[10];
- int occ;
- do {
- printf("Enter name:");
- scanf("%s", name1);
- printf("Enter type:");
- scanf("%s", type1);
- printf("Enter occurance:");
- scanf("%d", &occ);
- newnode = (struct list *)malloc(sizeof(struct list));
- newnode->link = NULL;
- newnode->prev = NULL;
- newnode->name = name1;
- newnode->type = type1;
- newnode->occurance = occ;
- if(newnode == NULL) {
- printf("Memory could not be allocated!");
- // exit(0);
- }
- if(start == NULL) {
- start = newnode;
- ptr = start;
- printf("start is: %s", start->name);
- }
- else if(start->link == NULL) {
- start->link = newnode;
- newnode->prev = start;
- ptr = newnode;
- }
- else {
- ptr->link = newnode;
- newnode->prev = ptr;
- ptr = ptr->link;
- }
- printf("Enter 1 to continue: ");
- scanf("%d", &choice);
- } while(choice == 1);
- // display
- ptr = start;
- while(ptr != NULL) {
- printf("%s ", ptr->name);
- printf("%s ", ptr->type);
- printf("%d n", ptr->occurance);
- ptr = ptr->link;
- }
- }
- newnode->name=name1;
- newnode->type=type1;
- strcpy(newnode->name, name1);
- strcpy(newnode->type, type1);
- //allocate memory of node's name attribute with the same amount as name1 (+1 for null terminating character)
- newnode->name = malloc(sizeof(char) * (strlen(name1)+1));
- newnode->type= malloc(sizeof(char) * (strlen(type1)+1));
- struct list {
- char *name;
- char *type;
- // other members
- };
- // after allocating memory for a new node
- newnode->name = name1; // name1 evaluates to a pointer to name1[0]
- newnode->type = type1; // type1 evaluates to a pointer to type1[0]
- newnode->name = strdup(name1); // make a copy of name1 before it's overwritten
- newnode->type = strdup(type1); // make a copy of type1 before it's overwritten
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement