Home > Net >  A global struct pointer is used, but it does not take input. In C
A global struct pointer is used, but it does not take input. In C

Time:02-12

The input lines are marked beside. Here, *ptr is a global struct pointer. In the main function, the get_data() function is called but it does not take any input rather the program terminates.

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

    struct detail
    {
        int present, absent, credit, left_weeks;
    };

    struct detail *ptr;             // global

    void get_data()
    {
        printf("\nYou have opted for Entering the data \n");
        printf("\nEnter the number of presents - ");
        scanf("%d",&ptr->present);                                       // First input

        printf("\nEnter the number of absents - ");
        scanf("%d",&ptr->absent);                                        // Second input

        printf("\nEnter the subject credit - ");
        scanf("%d",&ptr->credit);                                        // Third input

        printf("\nEnter the number of weeks left - ");
        scanf("%d",&ptr->left_weeks);                                    // Fourth input
    }

    int main()
    {
        get_data();
    }

I have checked in visual studio code and also an online compiler. Could anyone help.

CodePudding user response:

ptr points nowhere. And there is no variable of type struct detail in this code.

You probably want this:

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

struct detail
{
    int present, absent, credit, left_weeks;
};

struct detail foo;         // << the actual variable you forgot
struct detail *ptr = &foo;             // globalptr points to foo
...

and all your scanfs are wrong, the %d specifier wants a pointer to int but you provide an int.

You want this:

scanf("%d", &ptr->present);
            ^you forgot this

That being said, your approach is overly complicated, you probably just want this:

scanf("%d", &foo.present);

and remove the global ptr pointer alltogether.

CodePudding user response:

already answered but I want to elaborate.

struct detail *ptr; 

creates a pointer whose job is to point at an instance of detail. but you have not told it which one to point at (Imagine you had several instances of details in you program). In fact you dont have any instances of detail yet.

So you have to create an instance of detail

On the stack and set ptr to point at it

 int main (..){
   ...
   struct detail d; 
   ptr = &d;   

On the heap

 int main (..){
   ...
   struct detail *d = malloc(sizeof(struct detail));
   ptr = d;  // d is a pointer already here

Or static global

  struct detail d;
  ....
  int main(..){

    ....
    ptr = &d;
  • Related