【问题标题】:Passing an element of an array of structs in C在 C 中传递结构数组的元素
【发布时间】:2014-04-14 12:29:34
【问题描述】:

我试图传递我制作的 20 个“数据库”结构之一

这是我的函数“add”的原型

void add(struct database test);

我想传递我的数据库结构,现在我称之为“测试”

这是我的数据库结构

struct database
{
    char ID[6];
    char Duration[3];
};

main()
{

   char menu;
   struct database employee[20]; // I make 20 employee variables
   int a = 0;                    /*A counter I use to edit certain structs 
                                   ie a=2  "employee[a]" = "employee[2]" */

然后我像这样调用函数:

add(employee[a]);
a++;  /*Once it exits this I want it to go to the next employee
       variable so I increment the counter */

实际功能如下:

void add(struct database test)
{
    static int a = 0;

    printf("\nPlease enter a 5 digit employee number: ");
    scanf("%s", test[a].ID);

    a++
}

执行此操作时出现错误:

错误 E2094 Assignment.c 64: 'operator+' 未在函数 add(database) 中的“int”类型参数的“数据库”类型中实现

它说错误发生在

scanf("%s", test[a].ID);

提前感谢您的帮助,如果我格式错误,我很抱歉,仍在学习使用堆栈溢出,非常抱歉!

【问题讨论】:

  • 为什么不能将结构指针传递为 void add(struct database *test);,更改 add(employee[a]);到 add(&employee[a]); 和 scanf("%s", test[a].ID);到 scanf("%s", test->ID);

标签: c function struct parameter-passing argument-passing


【解决方案1】:

这是您需要做的事情才能做到这一点:

void add(struct database* test)
{
    printf("\nPlease enter a 5 digit employee number: ");
    scanf("%s",test->ID);
}

int main()
{
    ...
    int a;
    struct database employee[20];
    for (a=0; a<sizeof(employee)/sizeof(*employee); a++)
        add(&employee[a]); // or add(employee+a);
    ...
}

【讨论】:

    【解决方案2】:

    add(struct database test)struct database 声明为参数。这不是一个数组,所以你不能索引它。

    所以

    test[a]
    

    无效。


    此外,add() 中的 int amain() 中定义的 int a 不同。在add() 内部,后者a 被前者a 隐藏。


    另外^2,您将向add() 传递main() 中声明的数组元素的副本。因此,当从add() 返回时,对add() 侧的test 所做的任何修改都会丢失。它们在main() 声明的数组中不可见。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-10
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多