C 二进制+;(有';结构学生';和';int';)
我试图从函数返回一个结构变量,我创建了一个函数getInformation来获取数据,但我得到了一个错误,错误是“无效操作数到二进制+(有'struct student'和'int')”,这是什么意思?我怎样才能修好它C 二进制+;(有';结构学生';和';int';),c,function,struct,malloc,structure,C,Function,Struct,Malloc,Structure,我试图从函数返回一个结构变量,我创建了一个函数getInformation来获取数据,但我得到了一个错误,错误是“无效操作数到二进制+(有'struct student'和'int')”,这是什么意思?我怎样才能修好它 int main(){ struct student *s1; int n; printf("Enter how many data: "); scanf("%d", &n); s1 =(struct student
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;
}
错误原因:
scanf(“%d”,(s+i)->age)代码>。这里,s
不是指向结构的指针。因此,添加i
会产生错误,因为s
和i
都属于不同的类型(s
属于struct student
类型,但i
属于int
类型)
(s+i)->age
这似乎是错误的,因为s
是一个结构,而不像s1
那样是一个指针。您可能应该改为使用s1
,但在这种情况下,s
的作用不清楚……函数调用和函数定义是不同的。函数调用没有任何参数。
struct student {
int age;
float marks;
};
#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;
}
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