2015-04-04 82 views
0

让我们说我们有那些2结构:C结构成员的功能

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); 
} 

我的理解是,如果IM定义一个员工,我想打印他的出生日期,我会做:

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

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

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

非常感谢。

+3

'Employee * emp; emp =(Employee *)(malloc(sizeof(Employee)); emp-> dateOfBirth.date = 2;'... – BLUEPIXY 2015-04-04 21:38:21

+0

根据编译器的不同, struct Employee'或使用类型定义,如'typedef struct {...} Employee'。 – holgac 2015-04-04 21:38:48

+0

或'Employee emp = {“”,0,0.0f,{2,2,1948}};'''printBirth(emp。 ' – BLUEPIXY 2015-04-04 21:41:21

回答

0

试试这个代码

#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当youre使用结构。如果您使用的是typedef您不再需要通过使用typedef代码来编写struct更清洁,因为它提供了更多的抽象化代码