gpt4 book ai didi

c - 错误: used struct type value where scalar is required for(;*ptr;ptr++)

转载 作者:行者123 更新时间:2023-11-30 16:47:09 68 4
gpt4 key购买 nike

您能否解释一下此错误背后的原因。

错误代码:

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

}
}

最佳答案

增加引用特定地址处的值的指针,而不是该指针地址处的值。 *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);

}

关于c - 错误: used struct type value where scalar is required for(;*ptr;ptr++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43426683/

68 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com