Loop problem in C

I am writing a simple program in c to better understand the language, but I have a strange problem. As the code below shows, I only have one loop that it completes when I insert 255 as the value. The problem is that when I select the first (insertion option), and after I insert the name, the program starts something like a loop and gives me the selection screen all the time ...

#include<stdio.h>
#include<stdlib.h>
struct student{
    char *name;
    int id;
    };
void insertStudent(void);
struct student * init(void);    

int main(){
    struct student *p;
    int selectionCode=0;

    while(selectionCode!=255){
        printf("\nInsert students:1");
        printf("\nDisplay students:2");
        printf("\nExit:255");
        printf("\n\nEnter selection:");
        scanf("%d",&selectionCode);

        p=init();

        switch(selectionCode){
            case 1:
            insertStudent();
            //printf("1\n");
            break;
            case 2:
            //printf("2\n");
            break;
            case 255:
            break;
            }
        }

    //p->name="stelios";
    //p->id=0;
    //printf("Name:%s ID:%d",p->name,p->id);
    //free(p);
    //p=NULL;

    return 0;
}
struct student *init(void)
{
    struct student *p;
    p=(struct student *)malloc(sizeof(struct student));
    return p;
}
void insertStudent(void){
    struct student *p;
    p=init();
    printf("Enter Name:");
    scanf("%s",p->name);//return 1;
    printf("Enter ID:");
    scanf("%d",&p->id); 
    //printf("test");
    }
+3
source share
6 answers

, name . init , name. insertStudent scanf . "" , .

+2

, , p insertStudent().

return 1; insertStudent(), .

0

"return 1;" insertStudent, .

p- > malloc "scanf" ( "% s", p- > name); to "scanf (" % s ", & p- > name);", * char.

0

"return 1;" . , , . , "void", .

: , .

0

:

struct student *insertStudent(void){
struct student *p;
p=init();
printf("Enter Name:");
scanf("%s",p->name);
printf("Enter ID:");
scanf("%d",&p->id); 
//printf("test");
 return p;
}

 case 1:
free(p);
    p=insertStudent();
    //printf("1\n");  

init .

0

...:-) malloc() p- > name, , scanf(). . ... p . , , , , . : return 1; , scanf() insertStudent(), " " . void, , , . , .

, - , , , , .

0

All Articles