[英]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?我试图从 function 返回一个结构变量,我创建了一个 function getInformation 来获取数据,但我收到错误消息“二进制 + 的操作数无效(具有 'struct student' 和 'int')” ,这是什么意思? 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;
};
Reason for error: scanf("%d",(s+i)->age);
错误原因:
scanf("%d",(s+i)->age);
. . Here,
s
is not a pointer to structure.这里,
s
不是指向结构的指针。 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
).所以,添加
i
会给你错误,因为s
和i
都是不同的类型( s
是struct student
类型,但i
是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: output 是:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.