简体   繁体   中英

C struct member within struct to function

Let say we have those 2 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.

I know that it would be easier if the function would work with a pointer of struct date but i dont have that option. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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