结构中的C结构成员将运行
假设我们有两个结构:结构中的C结构成员将运行,c,function,struct,arguments,member,C,Function,Struct,Arguments,Member,假设我们有两个结构: 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 -
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,那么就不需要到处编写struct了,因为typedef代码更简洁,因为它提供了更多的抽象Employee*emp;emp=员工*mallocsizeofEmployee;emp->dateOfBirth.date=2;。。。根据编译器的不同,您可能需要使用类似struct Employee的struct前缀Employee和date,或者使用类似typedef struct{…}Employee.or Employee emp={,0,0.0f,{2,21948};。。打印出生日期;BLUEPIXY的第一个答案帮了我很多忙。现在一切都好了。谢谢。我没有办法回答这个问题,我不知道怎么做。通常,我看到一个大的复选标记,我可以用绿色标出。。