【问题标题】:Getting input using pointer to array of structures and printing the output使用指向结构数组的指针获取输入并打印输出
【发布时间】:2015-08-04 07:37:42
【问题描述】:

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

【问题讨论】:

  • 欢迎来到 SO。由于以下原因,您的“问题”可能不会得到回答。 1)你不问任何问题。 2)您只是复制粘贴了一些代码并且没有正确格式化(这读起来很不愉快)。 3)您没有正确使用标签:您至少应该为您的问题的编程语言添加一个标签。 4)评论您的代码,为任何愿意帮助您的人提供有用的信息。提问方式请参考this guide

标签: arrays pointers structure


【解决方案1】:

在您的代码中有很多问题,首先您需要在您的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;
}

【讨论】:

  • 感谢 Nishant..我使用 dot 和 -> 的原因是我只是在使用不同类型的指令进行测试
  • 如果这个答案对你有帮助,你可以接受这个答案
猜你喜欢
  • 1970-01-01
  • 2021-09-23
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
  • 2013-04-13
  • 1970-01-01
  • 1970-01-01
  • 2017-06-03
相关资源
最近更新 更多