使用指向结构数组的指针获取输入并打印输出

Getting input using pointer to array of structures and printing the output

我正在尝试使用 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++; 
  } 
} 

在你的代码中有很多问题,首先你需要在你的scanf语句中更改sptr++,因为每个sptr++都会增加你的指针1个索引和我相信你不是故意的。其次,我不明白为什么你对不同的数据类型使用不同的语法,你需要先读一本书。即使在您的 printf 语句中,有时您使用 -> 运算符,有时使用点,您到底为什么要这样做?您发布的这段代码是否编译通过了?

我已经修好了。

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