Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error when assigning values to members in structures using scanf

I’m trying to create a linked list using C. This is the code that I have now.

//fig 12_4.c

#include <stdlib.h>
#include <stdio.h>
#include <string.h>


struct gradeNode{
    char lastName[20];
    double grade;
    struct gradeNode *nextPtr;
};


void insert(GradeNodePtr);

int main(void)
{
    //part a
    struct gradeNode *startPtr = NULL;

    //part b
    struct gradeNode *newPtr = malloc(sizeof(GradeNode));
    startPtr = newPtr; 

    // checking to see if memory was allocated properly 
    if(newPtr != NULL)
    {
        newPtr->grade = 91.5;
        strcpy(newPtr->lastName,"Jones");
        newPtr->nextPtr = NULL;
    }

    //part c
    for(int i = 0; i<4; i++)
    {
      struct gradeNode *newPtr = malloc(sizeof(GradeNode));

      if(newPtr != NULL)
      {
        printf("Please Type A grade: ");
        scanf("%lf",newPtr->grade);
        printf("Please Enter a LastName: ");
        scanf("%s",newPtr->lastName);
        puts("");
      }
      else
      {
        puts("No memory available. Critical Error!");
      }
    }
}

If you look at the for loop under the comment labeled part c you may be able to find my error. After the scanf("%lf",newPtr->grade); line of code is ran the execution process stop. Therefore, the scanf function to enter lastname is never reached and the for loop doesn’t loop 3 times. Does anyone know where I’m going wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

scanf expects to receive pointers. newPtr->grade is not a pointer.

scanf("%lf", &newPtr->grade);

As always, you should check the return from scanf to ensure the data was successfully read.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading