我正在尝试使用scanf
函数将数据转换为带有指针的结构数组。然后我试图打印输出。但是在printf
执行后输出显示没有值。需要帮助我哪里出错了?
这是我的代码:
#include<stdio.h>
struct estore
{
int pid;
char category[20];
char brand[20];
char model[20];
int price;
}; //can also be 'stock[5];' The below line is not required in such case
struct estore stock[5];
struct estore *sptr=stock;
void main()
{
int j;
for(j=0;j<5;j++)
{
printf("\nEnter Product ID: ");
scanf("%d",&(sptr++)->pid);
printf("\nEnter Product Category: ");
scanf("%s",(sptr++)->category);
printf("\nEnter Product Brand: ");
scanf("%s",(sptr++)->brand);
printf("\nEnter Product Model: ");
scanf("%s",(sptr++)->model);
printf("\nEnter Product Price: ");
scanf("%d",&(sptr++)->price);
}
for(j=0;j<5;j++)
{
printf("\nThe Product ID is %d",sptr->pid);
printf("\nThe Product Category is %s",(*sptr).category);
printf("\nThe Product Brand is %s",sptr->brand);
printf("\nThe Product Model is %s",sptr->model);
printf("\nThe Product Price is Rs.%d/-",(*sptr).price);
sptr++;
}
}
答案 0 :(得分:0)
在您的代码中存在许多问题,首先您需要在sptr++
语句中更改scanf
,因为每个sptr++
将使用1个索引递增指针而我是确定你不打算这样做。其次,我不明白你为什么使用不同的语法来处理不同的数据类型,你需要先阅读一本书。甚至在你的printf语句中,有时你正在使用 - &gt;操作员,有时候点,你为什么要在地球上做?您发布的此代码是否已编译?
我修好了。
int main()
{
int j;
for (j = 0; j<2; j++)
{
printf("\nEnter Product ID: ");
scanf("%d", &(sptr+j)->pid);
printf("\nEnter Product Category: ");
scanf("%s", &(sptr+j)->category);
printf("\nEnter Product Brand: ");
scanf("%s", &(sptr+j)->brand);
printf("\nEnter Product Model: ");
scanf("%s", &(sptr+j)->model);
printf("\nEnter Product Price: ");
scanf("%d", &(sptr+j)->price);
}
for (j = 0; j<2; j++)
{
printf("\nThe Product ID is %d", (sptr+j)->pid);
printf("\nThe Product Category is %s",(sptr+j)->category);
printf("\nThe Product Brand is %s", (sptr+j)->brand);
printf("\nThe Product Model is %s", (sptr+j)->model);
printf("\nThe Product Price is Rs.%d/-", (sptr+j)->price);
}
return 0;
}