C Doubly Linked List Program -
i have been writing c program work doubly linked lists. not work on dev cpp. can point out error? works until part add new record , crashes. i'm guessing there problem scanf() function.
//c double-linked list program struct stu { int roll,ph,ch,ma; stu *plink,*nlink; }; void addstu(stu *p,stu *n) { //add stu *s; int roll,ph,ch,ma; printf("hello student!\nyour roll no.? "); scanf("%d",&roll); printf("\nphysics score? "); scanf("%d",&ph); printf("\nchemistry? "); scanf("%d",&ch); printf("\nmath? "); scanf("%d",&ma); s->roll=roll; s->ph=ph; s->ch=ch; s->ma=ma; s->plink=p; s->nlink=n; } void remstu(stu *s) { //remove stu *next; next->plink=s->nlink; free(s); } // main function int main() { stu *s; int choice=0, ct=0; while(choice!=4) { printf("\n\t\twelcome records\n\n1. add\n2. remove\n3. see\n4. exit\nenter choice(1-4): "); scanf("%d",&choice); switch(choice) { case 1: stu *t; addstu(s,t); s=t; free(t); ++ct; break; case 2: remstu(s); break; case 3: for(int i=0;i<ct;++i) { printf("\n\nroll no. %d\nphysics %d\nchemistry %d\nmath %d",s->roll,s->ch,s->ph,s->ma); s=s->plink; } break; case 4: exit(0); break; default: printf("please enter correct choice(1-4)!"); } } return 0; }
s->roll=roll;
the pointer s
in function addstu()
never initialized , dereferencing leads undefined behavior hence crash.
do
s = malloc(sizeof(struct stu)); /* allocate memory */
i hope have
typedef struct stu stu;
Comments
Post a Comment