Rah*_*hul -2 c struct pointers arguments function
让我们有一个名为Employee的结构:
struct Employee
{
int basicsalary;
int bonus;
int netsalary;
};
Run Code Online (Sandbox Code Playgroud)
让我们有一个函数原型如下:
int calc_NetSalary(struct Employee**,int);
Run Code Online (Sandbox Code Playgroud)
让main函数声明结构数组的变量,如下所示:
struct Employee emp[100];
Run Code Online (Sandbox Code Playgroud)
让函数在main中调用如下:
for (i = 0; i < n; i++)
{
emp[i].netsalary = calc_NetSalary(emp[i],n); // Warning is here
}
Run Code Online (Sandbox Code Playgroud)
让函数定义如下:
int calc_NetSalary(struct Employee** emp,int n)
{
int i;
for(i = 0; i < n; i++)
{
emp[i]->netsalary = emp[i]->basicsalary + emp[i]->bonus;
}
return emp[i]->netsalary;
}
Run Code Online (Sandbox Code Playgroud)
我不知道作为一个参数传递什么,该函数需要一个带有两个星号的参数(代替emp上面的).我正在收到警告passing argument 1 of ‘calc_NetSalary’ from incompatible pointer type.我知道这一定是一个愚蠢的错误,或者我不清楚指针的概念.请帮忙 !
扩展我的评论:
该calc_netSalary函数期望数据的emp布局如下:
+---+ +-------------+-------+-----------+
emp: | | emp[0] -------> | basicsalary | bonus | netsalary |
+---+ +-------------+-------+-----------+
| | emp[1] ----+
+---+ | +-------------+-------+-----------+
| | emp[2] -+ +--> | basicsalary | bonus | netsalary |
+---+ | +-------------+-------+-----------+
... |
| +-------------+-------+-----------+
+-----> | basicsalary | bonus | netsalary |
+-------------+-------+-----------+
Run Code Online (Sandbox Code Playgroud)
也就是说,每个emp[i]都是指向实例的指针struct Employee.
然而,你的声明emp中main是这样的:
+-------------+-------+-----------+
emp: | basicsalary | bonus | netsalary | emp[0]
+-------------+-------+-----------+
| basicsalary | bonus | netsalary | emp[1]
+-------------+-------+-----------+
| basicsalary | bonus | netsalary | emp[2]
+-------------+-------+-----------+
...
Run Code Online (Sandbox Code Playgroud)
也就是说,每一个emp[i]是一个实例的struct Employee.
empin 的声明main是错误的,或者定义calc_netSalary是错误的; 他们不能一起工作.为了emp在main比赛了什么calc_netSalary期望,它需要被宣布下列方式之一进行初始化:
struct Employee **emp = malloc( sizeof *emp * 100 );
if ( emp )
for ( size_t i = 0; i < 100; i++ )
emp[i] = malloc( sizeof *emp[i] );
Run Code Online (Sandbox Code Playgroud)
要么
struct Employee *emp[100];
for ( size_t i = 0; i < 100; i++ )
emp[i] = malloc( sizeof *emp[i] );
Run Code Online (Sandbox Code Playgroud)
如果emp确实应该声明为数组struct Employee,那么calc_netSalary函数需要更改如下:
int calc_netSalary(struct Employee* emp,int n)
{
int i;
for(i = 0; i < n; i++)
{
emp[i].netsalary = emp[i].basicsalary + emp[i].bonus;
}
return emp[i].netsalary;
}
Run Code Online (Sandbox Code Playgroud)
如果你被告知申报emp为数组struct Employee,并找出办法将它传递给calc_netSalary这样它将作为数组来处理指针来struct Employee,然后给您提供一个不可能完成的任务.作业有些严重错误.
编辑
实际上,还有第三种方法,但它涉及声明第二个数组main并将其作为参数传递:
struct Employee emp[100];
struct Employee *emp2[100];
for ( size_t i = 0; i < 100; i++ )
emp2[i] = &emp[i];
...
calc_netSalary( emp2, 100 );
Run Code Online (Sandbox Code Playgroud)
但我假设作业要求你使用emp.