在C中传递结构数组的元素
我试图通过我制作的20个“数据库”结构中的一个 这是我的函数“add”的原型 我想通过我的数据库结构,现在我只把它称为“测试” 这是我的数据库结构在C中传递结构数组的元素,c,function,struct,parameter-passing,argument-passing,C,Function,Struct,Parameter Passing,Argument Passing,我试图通过我制作的20个“数据库”结构中的一个 这是我的函数“add”的原型 我想通过我的数据库结构,现在我只把它称为“测试” 这是我的数据库结构 struct database { char ID[6]; char Duration[3]; }; main() { char menu; struct database employee[20]; // I make 20 employee variables int a = 0;
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++
}
实际函数如下所示:
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赋值。c 64:“运算符+”未在函数add(数据库)中“int”类型参数的“数据库”类型中实现
它说错误在
scanf("%s", test[a].ID);
提前感谢您的帮助,我很抱歉,如果我格式化错误,仍然在学习如何使用堆栈溢出,非常抱歉 add(struct-database-test)
声明一个struct-database
作为参数。这不是数组,因此无法对其编制索引
所以
这是无效的
而且
add()
内部的int a
与main()
中定义的int a
不同。在add()
内部,后者a
被前者a
隐藏
另外^2您将向
add()
传递在main()
中声明的数组元素的副本。因此,从add()
返回时,对test
侧add()
所做的任何修改都将丢失。在main()
中定义的数组中,它们将不可见。这是您需要执行的操作,以使其正确:
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);
...
}
void添加(结构数据库*测试)
{
printf(“\n请输入一个5位数的员工编号:”);
scanf(“%s”,测试->ID);
}
int main()
{
...
INTA;
结构数据库职员[20];
对于(a=0;a为什么不能将结构指针作为void add(struct database*test)传递;将add(employee[a])更改为add(&employee[a]);并将scanf(“%s”,test[a].ID);更改为scanf(“%s”,test->ID);