Search code examples
cfunctionstructmallocstructure

invalid operands to binary + (have 'struct student' and 'int')


I am trying to return a structure variable from the function, i created a function getInformation to get the data but i got an error said "Invalid operands to binary + (have 'struct student' and 'int')", What does it mean? and how can i fix it?

 int main(){
 struct student *s1;
 int n;
 
printf("Enter how many data: ");
scanf("%d", &n);
 
s1 =(struct student *) malloc(n *sizeof(struct student));  

if ( s1 == NULL) 
{
    printf("memory not available");
    return 1; // exit(1); stlib.h
}

for(int i = 0; i < n; i++ ) 
{
    printf("\nEnter details of student %d\n\n", i+1);
     *s1 = getInformation();
}

}
    
struct student getInformation(struct student *s1,int i)   
{   
  struct student s;

    scanf("%d", (s+i)->age);    

    printf("Enter marks: ");
    scanf("%f", (s+i)->marks);

  return s;
}                   
    

Here is my structure

struct student {                                                    
int age;
float marks; 
};
    

Solution

  • Reason for error :scanf("%d",(s+i)->age);. Here, s is not a pointer to structure. So, adding i gives you error, because both s and i are of different types ( s is of type struct student but i is of type int).

    #include <stdio.h>
    #include<stdlib.h>
    struct student
    {
        int age;
        float marks;
    };
    
    struct student getInformation(struct student *s1);
    
    int main()
    {
        struct student *s1;
        int n;
    
        printf("Enter how many data: ");
        scanf("%d", &n);
    
        s1 = malloc(n * sizeof(struct student));
    
        if (s1 == NULL)
        {
            printf("memory not available");
            return 1; // exit(1); stlib.h
        }
    
        for (int i = 0; i < n; i++)
        {
            printf("\nEnter details of student %d\n\n", i + 1);
            *(s1+i) = getInformation(s1+i); //Changed the function call
        }
    
        for(int i=0;i<n;i++)
        {
            printf("%d ",s1[i].age);
            printf("%f ",s1[i].marks);
    
        }
    }
    
    struct student getInformation(struct student *s1)
    {
        
        scanf("%d", &(s1->age));
    
        printf("Enter marks: ");
        scanf("%f", &(s1->marks));
    
        return *s1;
    }
    

    The output is :

    Enter how many data: 3
    
    Enter details of student 1
    
    23
    Enter marks: 67
    
    Enter details of student 2
    
    34
    Enter marks: 99
    
    Enter details of student 3
    
    24
    Enter marks: 56
    23 67.000000 34 99.000000 24 56.000000