简体   繁体   English

在C中结合Struct + malloc

[英]combinding Struct + malloc in C

I am trying to make a malloc based on a struct. 我正在尝试基于结构进行malloc。

The struct looks like this: 该结构如下所示:

    struct shirts
        {
        char color[10];
        int size;
        };

struct shirts* ptr_shirts;

I then want to make x amount of t-shirts so i have a variable for that: 然后,我想制作x数量的T恤,所以我有一个变量:

printf("How many T-shirts? ");
            scanf("%d",&amount);
            getchar();
            ptr_shirts = (struct shirts *)malloc(amount * sizeof(struct shirts));

I then want to fille the spaces but i dont know how to do it. 然后,我想填补空间,但我不知道该怎么做。 I have tried to use a for loop and put in values like it is an array: 我试图使用一个for循环,并像数组一样放入值:

for(i = 0; i<amount;i++)
            {
            printf("Color on T-shirt nr %d: ",(i+1));
            scanf_s("%s", "what to type here" ,sizeof(ptr_shirts->color));
            printf("Size on T-shirt nr %d: ",(i+1));
            scanf("%d",&"what to type here");
            }

i have tried with 我尝试过

ptr_shirts[i].size
ptr_shirts->size[i]
(ptr_shirts.size 
and then ptr_shirts++)

but i dont know how to make it easy becuase i want to fill more then 1 t-shirt, thats the problem i got 但我不知道该如何轻松地做,因为我想再填充一件T恤,这就是我遇到的问题

For color array member note that scanf_s function is non-standard (well, to be honest in except to C11 with (optional though) Annex B, but it's not well-adopted yet), you might use fgets() along with stdin as an "safer" alternative. 对于color数组成员,请注意scanf_s函数是非标准的(嗯,老实说,除了带有附件B的C11(但可选),但尚未被广泛采用),您可以将fgets()stdin用作“更安全”的选择。

In case of size member it should be just: 如果是size成员,则应为:

&ptr_shirts[i].size

(that is: scanf("%d", &ptr_shirts[i].size); ) (即: scanf("%d", &ptr_shirts[i].size);

or alternatively: 或者:

&(ptr_shirts + i)->size

Couple of additional notes: 几个附加说明:

Try This -
ptr_shirts = (struct shirts *)malloc(amount * sizeof(struct shirts));

for(i = 0; i<amount;i++)
        {
           memset (ptr_shirts[i],0,sizeof(struct shirts)); /*Assign structure variable to NULL*/
           printf("Color on T-shirt nr %d: ",(i+1));
           scanf_s("what to type here %s", ptr_shirts[i].color,_countof(ptr_shirts[i].color));
           printf("Size on T-shirt nr %d: ",(i+1));
           scanf_s("what to type here %d", ptr_shirts[i].size,_countof(ptr_shirts[i].size));
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM