[英]combinding Struct + malloc in C
我正在嘗試基於結構進行malloc。
該結構如下所示:
struct shirts
{
char color[10];
int size;
};
struct shirts* ptr_shirts;
然后,我想制作x數量的T恤,所以我有一個變量:
printf("How many T-shirts? ");
scanf("%d",&amount);
getchar();
ptr_shirts = (struct shirts *)malloc(amount * sizeof(struct shirts));
然后,我想填補空間,但我不知道該怎么做。 我試圖使用一個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");
}
我嘗試過
ptr_shirts[i].size
ptr_shirts->size[i]
(ptr_shirts.size
and then ptr_shirts++)
但我不知道該如何輕松地做,因為我想再填充一件T恤,這就是我遇到的問題
對於color
數組成員,請注意scanf_s
函數是非標准的(嗯,老實說,除了帶有附件B的C11(但可選),但尚未被廣泛采用),您可以將fgets()
與stdin
用作“更安全”的選擇。
如果是size
成員,則應為:
&ptr_shirts[i].size
(即: scanf("%d", &ptr_shirts[i].size);
)
或者:
&(ptr_shirts + i)->size
幾個附加說明:
malloc()
返回的值,因為它可能為NULL
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.