[英]C struct member within struct to function
假設我們有這兩個struct:
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
,則不再需要使用typedef代碼在各處編寫struct
,因為它提供了更多的smidgen抽象,因此更加簡潔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.