简体   繁体   English

C编程:将struct作为参数传递-函数

[英]C Programming: passing struct as a parameter - Function

I am trying Add a new ITEM to GI array, but this doesn't seem to work. 我正在尝试向GI数组添加新的ITEM,但这似乎不起作用。 I am hitting a brick wall here. 我在这里撞墙。 Can anyone advise please? 有人可以建议吗? I tried passing additem(GI, &Recs, 222) as shown below and updating values: 我尝试如下所示传递additem(GI,&Recs,222)并更新值:

#include <stdio.h>


   struct Item {
   double value;
   int unitno;
   int isTa;
   int quant;
   int minQuan;
   char name[31];
};

struct Item GI[21] = {
   { 41.4,1275,01,110,12,"Apples" },
   { 52.99,3826,02,220,24,"Melon" },
};
int Recs=20;
void additem(struct Item item[], int *Recs, int unit);
void addtest();


int main ()
{
addtest();
return 0;
}

void addtest() {
additem(GI, &Recs, 222); 
}

void additem(struct Item item[], int *Recs, int value)
{
printf("--== Adding values! ==--\n");
        GI[21].value=44.44;
        GI[21].quant=44;
        GI[21].minQuan=4;
        strcpy(Recs->name, "vGrape");
return 0;
}

No, it doesn't work. 不,它不起作用。 You can't dynamically add items to an array in c. 您不能将项目动态添加到c中的数组。 You need dynamic memory allocation for that, namely malloc() and family. 为此,您需要动态分配内存,即malloc()和family。

This is not a trivial matter, you can use malloc() 's sister realloc() to increase the size of a previously allocated portion of memory, but you should be careful not to do it too often because memory allocation is expensive in terms of computational time. 这不是一件容易的事,您可以使用malloc()的姐妹realloc()来增加先前分配的内存部分的大小,但是您应注意不要过于频繁地这样做,因为就内存分配而言,这很昂贵。计算时间。

大小为21的数组只能采用索引0-20。

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

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