简体   繁体   中英

Functions containing Array of Structures in C

I made this structure to store entries but when I compute the total I'm getting a garbage value.I went through it a lot of times but still could not find the mistake.I also tried initializing the total but couldn't get he required answer .Every time I compute the total it gives the same garbage value as earlier.

#include <stdio.h>
#include <stdlib.h>
typedef struct
{
    char name[50];
    int Assignment[5];
    int Test[2];
    int Endsem;
    int Total;



}student;
void read(student s[],int n)
{
    int i,j;
    for(i=0;i<n;i++)
    {
        printf("Enter the name of the student");
        scanf("%s",&(s[i].name));
        printf("Enter the assignment marks \n ");
        for(j=0;j<5;j++)
        {
            scanf("%d",&(s[i].Assignment[j]));
        }
        printf("\n Enter the Test marks \n ");
        for(j=0;j<2;j++)
        {
            scanf("%d",&(s[i].Test[j]));
        }
        printf("\n Enter the EndSem marks \n");
        scanf("%d",&(s[i].Endsem));
        printf("\n \n ");
    }
}
void compute(student s[],int n)
{
    int i,j,d=0,m=0;

    for(i=0;i<n;i++)
    {
        s[i].Total=0;
        for(j=0;j<5;j++)
        {
          d+=(s[i].Assignment[j]);
        }
        for(j=0;j<2;j++)
        {
           m+=(s[i].Test);
        }
        s[i].Total=(d+m+(s[i].Endsem));
        printf("\n The total is %d out of 100",(s[i].Total));
    }
}
void display(student s[],int n)
{
    int i,j;
    for(i=0;i<n;i++)
    {
        printf("The entries are");
        printf("%s",(s[i].name));
        printf("assignment marks \n ");
        for(j=0;j<5;j++)
        {
            printf(" \n %d",(s[i].Assignment[j]));
        }
        printf("\nTest marks \n ");
        for(j=0;j<2;j++)
        {
            printf("%d \n ",(s[i].Test[j]));
        }
        printf("\n EndSem marks \n");
        printf("%d \n",(s[i].Endsem));
    }
}
void main()
{
    student s[1];

    read(s,1);
    display(s,1);
    compute(s,1);
}

How to solve this?

The problem is in

  m+=(s[i].Test);

Test is an array, not a normal ( scalar ) variable. It points to (or decays to) the starting address of the first element of the array. Adding that to an int makes no sense here .

You might want to write

 m+=(s[i].Test[j]);

That said, as I already commented, you should rewrite the scanf() statements for

  • including the maximum field width to prevent buffer overfloe, like scanf("%49s",...) for an argument of array size 50
  • pass the array name, instead of the address of array, as %s expects a pointer-to-char array, like scanf("%49s",s[i].name);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM