简体   繁体   English

结构中的C结构成员起作用

[英]C struct member within struct to function

Let say we have those 2 struct : 假设我们有这两个struct:

struct date
{
   int date;
   int month;
   int year; 
};

struct Employee
   {
   char ename[20];
   int ssn;
   float salary;
   struct date dateOfBirth;
};

If i want to use a member of a struct to send it to a function, let say we have this function : 如果我想使用结构的成员将其发送给函数,可以说我们有以下函数:

void printBirth(date d){
   printf("Born in %d - %d - %d ", d->date, d->month, d->year);
}

My understanding is if im defining an Employee and i want to print his date of birth, i would do : 我的理解是,如果我要定义一个雇员,并且我想打印他的出生日期,我会这样做:

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

But when i do this, i get an error : warning: passing argument 1 of 'functionName'(in our case it would be printBirth) from incompatible pointer type. 但是当我这样做时,我得到一个错误:警告:从不兼容的指针类型传递'functionName'的参数1(在我们的例子中是printBirth)。

I know that it would be easier if the function would work with a pointer of struct date but i dont have that option. 我知道,如果该函数将与struct date的指针一起工作会更容易,但是我没有该选项。 The function must receive a struct date as parameters. 该函数必须接收一个结构日期作为参数。

So i wanted to know how am i suppose to pass a struct defined within a struct to a function. 所以我想知道我该如何将结构体中定义的结构体传递给函数。

Thank you very much. 非常感谢你。

try this code 试试这个代码

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

I want to advice to use typedef when youre working with structures. 我想建议您在使用结构时使用typedef if you're using typedef you no longer need to write struct all over the place by useing typedef code is more cleaner since it provides a smidgen more abstraction 如果您使用的是typedef ,则不再需要使用typedef代码在各处编写struct ,因为它提供了更多的smidgen抽象,因此更加简洁

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM