【问题标题】:C Programming: passing struct as a parameter - FunctionC 编程:将结构作为参数传递 - 函数
【发布时间】:2016-11-22 22:20:07
【问题描述】:

我正在尝试将新项目添加到 GI 数组,但这似乎不起作用。 我在这里撞了一堵砖墙。有人可以建议吗? 我尝试如下所示传递 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;
}

【问题讨论】:

  • 越界写入,未定义行为。
  • 您的 Item 数组的大小是多少?尝试计算数组中使用的空格数,并使用它来决定将插入新条目的位置。
  • @johnelemans 我想我不明白你的意思,插入一个数组?
  • strcpy(Recs-&gt;name, "vGrape"); : Recs 的类型是 int*
  • additem 应该将一个新项目插入到您称为 GI 的数组中。

标签: c struct structure


【解决方案1】:

不,它不起作用。您不能动态地将项目添加到 c 中的数组中。您需要为此进行动态内存分配,即malloc() 和家庭。

这不是小事,你可以使用malloc()的姐姐realloc()来增加之前分配的部分内存的大小,但是要注意不要太频繁,因为内存分配很昂贵在计算时间方面。

【讨论】:

  • 如果我将数组初始化为 GI[21] 那么我认为我们为该数组保留了内存?
  • 到目前为止,我只有 G[0] 和 G[1] 满了,其余的都是空的。我可以知道为什么我还需要 realloc 吗?
  • 你没有。看来您想要的项目比最初分配的要多,因为您使用了数组之外的 G[21]
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 2013-01-18
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    相关资源
    最近更新 更多