請您解釋此錯誤背後的原因。錯誤:使用struct type value((*; ptr; ptr ++)需要標量)
錯誤代碼:
used struct type value where scalar is required
for(;*ptr;ptr++)
"for the below code?
是否有任何理由,我們是不允許結構變量在for循環?
#include<stdio.h>
#include<stdlib.h>
struct student
{
char name[20]; // Given
int math; // Marks in math (Given)
int phy; // Marks in Physics (Given)
int che; // Marks in Chemistry (Given)
int total; // Total marks (To be filled)
int rank; // Rank of student (To be filled)
};
static int count=1;
void enter_data(struct student* arr,int num);
void print_data(struct student* arr,int num);
int main()
{
int num=1;
char ch;
printf("Enter the number of student records you want to input?..\n");
scanf("%d",&num);
struct student *arr=(struct student*)malloc(num*sizeof(struct student));
printf("Do you want to enter the student record...(Y/N)\n");
scanf(" %c",&ch);
if(ch=='y'||ch=='Y')
{
enter_data(arr,num);
printf("The created record is .....\n");
print_data(arr,num);
}
else
return 0;
}
void enter_data(struct student* arr,int num)
{
int i;
struct student* ptr=arr;
for(;count<=num;ptr++,count++)
{
printf("Enter the name of the candidate...\n");
scanf("%s",ptr->name);
printf("Enter the marks scored in maths,phy,che....\n");
scanf("%d%d%d",&ptr->math,&ptr->phy,&ptr->che);
((ptr->total)=(ptr->math)+(ptr->phy)+(ptr->che));
}
}
void print_data(struct student* arr,int num)
{
int i;
struct student* ptr=arr;
for(;*ptr!=NULL;ptr++)//error here
{
printf("Name of the candidate...%s\n",ptr->name);
printf("Enter the marks scored in maths...%d\t physics... %d\tche... %d\n total=%d\n",ptr->math,ptr->phy,ptr->che,ptr->total);
}
}
的誤差。即你正在比較'struct student'到'NULL'。那個解除引用不應該在那裏。我認爲所報告的錯誤消息「對二進制表達式無效的操作數('struct student'和'void *')」會使這一點變得明顯。而且,即使在修正之後,我不認爲這是你想要的結果。你需要一個在這個循環中的計數器。 – WhozCraig
實際上,您需要使用'num'而不是'ptr'來終止該循環。 – aschepler
我同意@aschepler。該循環可能更像'for(; num--; ++ ptr)'或類似的。 'ptr'的值確實不屬於條件。 – WhozCraig