错误:使用了struct type value,其中标量是必需的(; * ptr; ptr ++)

时间:2017-04-15 13:33:27

标签: c loops for-loop structure scalar-subquery

请你解释一下这个错误背后的原因。

错误代码:

  

在下面的代码中使用了需要标量的结构类型值for(;*ptr;ptr++)

为什么我们不允许在for循环中使用struct变量?

#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);

        }
}

1 个答案:

答案 0 :(得分:0)

增加引用特定地址处的值的指针,而不是该指针地址处的值。 *ptr!=NULL表示您正在将struct student与NULL

进行比较
 for(;ptr!=NULL;ptr++)//error fixed 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);

            }