Hello,
I'm new to C, and have been messing around with pointers. I have a program that creates a "movienode' struct that stores two ints and a char pointer (string).
When creating nodes in the program, the string are stored successfully in nodes I create. However, in my addMovie function I am apparently not storing the char correctly because upon calling printQueue I see that instead of a title I get giberish (example: �'� �)
I originally had *title instead of title[40] in addMovie, and had scanf save to &title instead of title... but printQueue would segfault.
If anyone could help me, I'd appreciate it.
Code:#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> struct movienode { char *title; int year; int id; struct movienode *next; }; //global head struct movienode *movie = NULL; //define void printQueue (struct movienode *); int main (void) { struct movienode *m1 = (struct movienode *) malloc(sizeof(struct movienode)); struct movienode *m2 = (struct movienode *) malloc(sizeof(struct movienode)); movie = m1; movie->year = 1985; movie->id = 1582; movie->title = "Movie1"; movie->next = m2; m2->year = 1955; m2->title = "Movie2"; m2->id = 1583; menu(); return 0; } void printQueue (struct movienode * h) { while (h != 0) { printf("Movie: %s Year: %d ID: %d",h->title, h->year, h->id); printf("\n"); h = h->next; } } void addMovie (struct movienode * h) { struct movienode *temp = (struct movienode *) malloc(sizeof(struct movienode)); char title[32]; int year; int id; printf("\nEnter movie title: "); scanf("%s", title); printf("\nEnter movie year: "); scanf("%d", &year); printf("\nEnter movie id: "); scanf("%d", &id); temp->id = id; temp->year = year; temp->title = title; temp->next = h; movie = temp; } int findMovie (struct movienode * h) { int id; int curid; printf("Enter movie ID to search for: "); scanf("%d", &id); while (h != 0) { if (h->id == id) { printf("Movie: %s Year: %d ID: %d", h->title,h->year,h->id); return 1; } else h=h->next; } printf("Not found."); return 0; } int delMovie (struct movienode * h) { int id; printf("Enter movie ID to delete: "); scanf("%d", &id); if (h->id == id) { movie = h->next; free(h); return 1; } while (h != 0) { if (h->next->id == id) { h->next = h->next->next; free(h->next); return 1; } else h=h->next; } printf("Not found"); return 0; } void menu(void) { int opt; while (opt != 0) { printf("\n\nMenu\n\n\n"); printf("1. Print Movies\n"); printf("2. Add Movie\n"); printf("3. Del Movie\n"); printf("4. Search Movies\n"); printf("0. Exit"); printf("\n\nEnter option: \n"); scanf("%d", &opt); if (opt == 1) printQueue(movie); else if (opt == 2) addMovie(movie); else if (opt == 3) delMovie(movie); else if (opt == 4) findMovie(movie); } }



LinkBack URL
About LinkBacks





