0

I am trying to use scanf() to input values to a structure using pointers.Can you help me to understand why my code is not working

This is my code:

#include<stdio.h>
struct student
{
   int no;
   float marks;
}st[2],*s;

main()
{
  printf("enter the values");
  for(s=st;s<st+2;s++)
  {
    scanf("%d%d",&s->no,&s->marks);
  }
  for(s=st;s<st+2;s++)
  {
    printff("%d\t%d\t",s->no,s->marks);
  }
}

in this code scanf is not working properly,it is taking only the first value

Yu Hao
  • 119,891
  • 44
  • 235
  • 294

3 Answers3

2

You are using the wrong format specifier. %d is used for ints while %f is used for floats. Use

scanf("%d%f",&s->no,&s->marks);

and

printf("%d\t%f\t",s->no,s->marks);

instead as s->marks is a float, not an int. Using the wrong format specifier leads to Undefined Behavior.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
0
 #include<stdio.h>
     struct student
       {
      int no;
      float marks;
         }st[2],*s;


 main()
  {
 printf("enter the values");
 for(s=st;s<st+2;s++)
  {
 scanf("%d%f",&s->no,&s->marks);
  }
 for(s=st;s<st+2;s++)
   {
  printf("%d\t%f\t",s->no,s->marks);
    }
   }

U have to use %f for float

jayprakashstar
  • 395
  • 2
  • 12
0

In the structure you have taken two variable one is int type and other is float type but while doing scanf(taking input) you are doing %d for float whereas it should be %f for float .This is a very minor mistake but you should try to avoid it on your own by just looking at your code carefully :)

Happy coding

Gyapti Jain
  • 4,056
  • 20
  • 40
Kunal Saini
  • 138
  • 10