Search code examples
cloopsnodes

Why it does not show the output in while loop?


I am trying to write a C code. It works correctly until GPA, but it does not continue and terminates after when I input the GPA. I do not understand its reason. What should I do to fix this problem?

Here is my codes:

NODE* create_list()
{
    NODE *first, *temp = 0, *newNode;
    first = 0;
    int choice = 1;
    head = (NODE *)malloc(sizeof(NODE));

    if (head == NULL)
    {
        printf("Unable to allocate memory.");
    }
    else
    {

        printf("Do you want to continue(Type 0 or 1)?\n");
        scanf_s("%d", &choice);
        while (choice)
        {

            newNode = (NODE *)malloc(sizeof(NODE));
            struct studentType studen;
            printf("Enter the data student Id:\n");
            scanf_s("%d", &studen.id);
            printf("Enter the data student Name:\n");
            scanf_s("%s", studen.name);
            printf("Enter the data student GPA:\n");
            scanf_s("%d", &studen.GPA);
            newNode->stud = studen; // Link data field of newNode with data
            newNode->ptr = NULL; // Link address field of newNode with NULL

            temp->ptr = newNode; // Link previous node i.e. temp to the newNode

            temp = temp->ptr;
            printf("Do you want to continue(Type 0 or 1)?\n");
            scanf_s("%d", &choice);


        }
    }
    temp->ptr = 0;


    return first;
}



Solution

  • *temp = 0
    

    Here, you initialize temp by NULL pointer.

    Then you try to access the ptr inside it without the initialization:

     temp->ptr = newNode;
    

    So, you have to initialize temp before working with this variable.