Home > Blockchain >  Error when assigning values to members in structures using scanf
Error when assigning values to members in structures using scanf

Time:09-20

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?

CodePudding user response:

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.

  • Related