从功能获取结构的输入

时间:2014-04-09 04:16:14

标签: c

我试图将一个结构发送到一个函数并在函数中填入正确值的结构,然后在main中显示该值,但是当我运行它时它不起作用。(i不能使用指针功能)。

 struct inventory{
                char name[20];
                int number;

                   };
void function(struct inventory items);
int main()
{
int x,y,z;
 struct inventory items;
function(items);
printf("\nam in main\n");
printf("\n%s\t",(items).name);
printf(" %i\t",(items).number); 
getch();    

    }
   void function(struct inventory items)
    {
printf(" enter the item name\n ");
scanf(" %s ",&(items).name );
printf(" enter the number of items\n ");
scanf("%i",&(items).number );
    }

(即:我不允许使用指针功能)如何在没有指针的情况下显示名称和数字。

2 个答案:

答案 0 :(得分:3)

struct inventory
{
    char name[20];
    int number;
};

struct inventory function();

int main()
{
    int x,y,z;
    struct inventory items;
    items=function();
    printf("\nam in main\n");
    printf("\n%s\t",(items).name);
    printf(" %d\t",(items).number); 
    getch();
}

struct inventory function()
{
    struct inventory items;
    printf(" enter the item name\n ");
    scanf(" %s ",&items.name );
    printf(" enter the number of items\n ");
    scanf("%d",&items.number );
    return items;
}

答案 1 :(得分:0)

你可以从函数返回结构引用,考虑下面给出的代码

 struct inventory{
  char name[20];
  int number;
 };

struct inventory function(struct inventory items);

int main()
{
 int x,y,z;
 struct inventory items,ret_itm;
 ret_itm=function(items);
 printf("\nam in main\n");
 printf("\n%s\t",(ret_itm).name);
 printf(" %i\t",(ret_itm).number); 
 getch();    

}

struct inventory function(struct inventory items)
{
  printf(" enter the item name\n ");
  scanf(" %s ",&(items).name );
  printf(" enter the number of items\n ");
  scanf("%i",&(items).number );
  return items;
}