[英]C struct member within struct to function
假设我们有这两个struct:
struct date
{
int date;
int month;
int year;
};
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date dateOfBirth;
};
如果我想使用结构的成员将其发送给函数,可以说我们有以下函数:
void printBirth(date d){
printf("Born in %d - %d - %d ", d->date, d->month, d->year);
}
我的理解是,如果我要定义一个雇员,并且我想打印他的出生日期,我会这样做:
Employee emp;
emp = (Employee)(malloc(sizeof(Employee));
emp->dateOfBirth->date = 2; // Normally, im asking the user the value
emp->dateOfBirth->month = 2; // Normally, im asking the user the value
emp->dateOfBirth->year = 1948; // Normally, im asking the user the value
//call to my function :
printBirth(emp->dateOfBirth);
但是当我这样做时,我得到一个错误:警告:从不兼容的指针类型传递'functionName'的参数1(在我们的例子中是printBirth)。
我知道,如果该函数将与struct date的指针一起工作会更容易,但是我没有该选项。 该函数必须接收一个结构日期作为参数。
所以我想知道我该如何将结构体中定义的结构体传递给函数。
非常感谢你。
试试这个代码
#include <stdio.h>
typedef struct
{
int date;
int month;
int year;
} date;
typedef struct
{
char ename[20];
int ssn;
float salary;
date dateOfBirth;
} Employee;
void printBirth(date *d){
printf("Born in %d - %d - %d \n", d->date, d->month, d->year);
}
int main ()
{
Employee emp;
emp.dateOfBirth.date = 2;
emp.dateOfBirth.month = 2;
emp.dateOfBirth.year = 1948;
printBirth(&emp.dateOfBirth);
}
我想建议您在使用结构时使用typedef
。 如果您使用的是typedef
,则不再需要使用typedef代码在各处编写struct
,因为它提供了更多的smidgen抽象,因此更加简洁
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.