将结构添加到数组中

adding structures into array

所以我的问题如下,我有一个像超市产品这样的产品,它是一个由标识符(标签)、重量和数量组成的结构,我有一个命令是 c.

我想做的是将产品添加到数组中并打印其重量。

#include <stdio.h>

int i = 0; // counts the number of products

struct product 
{
   char ident[64]; // string that identifies the product eg. "bread"
   int weight;
   int quant;
};

struct product sistem[10]; // array of products

void add(char ident,int weight,int quant);

struct product make_product(char ident,int weight,int quant)
{
    struct product p1 = {ident,weight,quant};   // creates a product and returns the created product
    return p1;
}

int main() {
    char c; int weight; char ident; int quant;
   scanf("%c %[^:]:%d:%d",&c,ident,&weight,&quant);
   add(ident,weight,quant);

   return 0;
}

void add(char ident,int weight,int quant)
{
   printf("New product %d\n",i);                           //
   sistem[i] = make_product(ident,weight,quant);           // adds a new product into an array of products
   printf("%d\n",sistem[i].weight);                       //
   i++;
}
My input: a bread:2:2

My output: New product 0
           0

Expected output: New product 0
                 2

所以基本上这并没有保存我在数组中创建的产品,我似乎不明白为什么没有。

因此,如果有人能提供帮助,我将不胜感激。

在 scanf 中,您使用 ident 作为单个字符,但它应该是 64 个字符的缓冲区。此更改将需要更改代码的其他部分以达到预期 char *ident。此外,您不能像这样使用编译时未知的字符串初始化结构成员,因此您必须使用 strcpy 例如。这应该有效

#include <stdio.h>
#include <string.h>

int i = 0; // counts the number of products

struct product 
{
   char ident[64]; // string that identifies the product eg. "bread"
   int weight;
   int quant;
};

struct product sistem[10]; // array of products

void add(char *ident,int weight,int quant);

struct product make_product(char *ident,int weight,int quant)
{
    struct product p1 = {"",weight,quant};   // creates a product and returns the created product
    strcpy(p1.ident, ident);
    return p1;
}

int main() {
    char c; int weight; char ident[64]; int quant;
   scanf("%c %[^:]:%d:%d",&c,ident,&weight,&quant);
   add(ident,weight,quant);

   return 0;
}

void add(char *ident,int weight,int quant)
{
   printf("New product %d\n",i);                           //
   sistem[i] = make_product(ident,weight,quant);           // adds a new product into an array of products
   printf("%d\n",sistem[i].weight);                       //
   i++;
}