struct 中的 C struct 成员函数

C struct member within struct to function

假设我们有这 2 个结构:

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 并且我想打印他的出生日期,我会这样做:

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)。

我知道如果函数可以使用结构日期的指针会更容易,但我没有那个选项。该函数必须接收一个结构日期作为参数。

所以我想知道如何将结构中定义的结构传递给函数。

非常感谢。

试试这个代码

#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 代码更清晰,因为它提供了更多的抽象