0

你能解释一下这个错误背后的原因吗?

错误代码:

在需要标量的情况下使用了结构类型值 for(;*ptr;ptr++)“以下代码?

为什么我们不允许在 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);

        }
}
4

1 回答 1

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

            }
于 2017-04-15T13:40:18.617 回答