-3

This program is returning garbage values in output of total marks and average marks. even after declaring s.total=0 and s.marks[15]=0 in the beginning of program

//student database
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
    struct student
{
    int name[20];
    int roll[5];
    int total;
    float avg;
    int marks[15];
};
    struct student s;
    int subject_no,i;
    s.total=0;
    s.marks[15]=0;  
    printf("Enter the name of student:\t");
    scanf("%s",s.name);
    printf("enter the roll no:\t");
    scanf("%d",&s.roll);
    printf("Enter the number of subjects:\t");
    scanf("%d",&subject_no);
    for(i=0;i<subject_no;i++)
{
    printf("Enter marks in subject %d:\t",i);
    scanf("%d",&s.marks);
    s.total=s.total+s.marks[i];
}
    printf("total marks are:%d\n",s.total);
    s.avg=(s.total)/(subject_no);
    printf("The average is :%d",s.avg);
    getch();
}
Jatin
  • 31,116
  • 15
  • 98
  • 163
john_conner
  • 162
  • 1
  • 14

3 Answers3

2

This is an illegal memory access: s.marks[15]=0.

If you have 15 entries in the array, then legal indexes are between 0 and 14.

So you can do s.marks[0]=0 or s.marks[6]=0, but you should not do s.marks[15]=0.

If you want to set the entire array to zero values, then you can iterate it:

for (i=0; i<sizeof(s.marks)/sizeof(*s.marks); i++)
    s.marks[i] = 0;

Or simply use memset:

memset(s.marks,0,sizeof(s.marks));
barak manos
  • 29,648
  • 10
  • 62
  • 114
  • -Everything you wrote was ok.But the problem with the program was something else.Actually i deleted the s.marks[15] line.It wasn't needed and declared the s.marks[i] in the for loop.But the real problem actually was==== i wrote %d in the last printf statement,but actually i declared it float.so i had to write %f.and the program started working. – john_conner Feb 13 '14 at 13:18
1

You should explicitly clear your s structure with

 memset (&s, 0, sizeof(s));

Of course your filling of s.marks[15] is out of bounds (undefined behavior and/or buffer overflow!!)

Your code never fills or uses s.roll[1] so why make s.roll an array?

At last, your first for loop should be

if (subject_no >= 15) exit(EXIT_FAILURE);
for(i=0;i<subject_no;i++) {
  printf("Enter marks in subject %d:\t",i);
  scanf("%d",&s.marks[i]);
  s.total=s.total+s.marks[i];
}
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

It would be better to store the name in a char array, rather than an int array (although that will work)

Also, you have been inconsistent in you use of scanf with arrays.

pecks
  • 318
  • 1
  • 2
  • 9