我有一組這樣的結構:
typedef struct month {
char cName[20];
char cAbbr[20];
int iDays;
int iNumber;
} MONTH;
它嵌套在另一個結構中:
typedef struct input{
MONTH * pMonths;
DATE sDate;
CALCS sCalcs;
} INPUT;
我像這樣在堆疊中初始化這個結構陣列:
MONTH * init_months(bool bLeap) {
MONTH months[NUM_MONTHS] = {
{ .cName = "January", .cAbbr = "Jan", .iDays = 31, .iNumber = 1 },
{ "February", "Feb", 28, 2 },
{ "March", "Mar", 31, 3 },
{ "April", "Apr", 30, 4 },
{ "May", "May", 31, 5 },
{ "June", "Jun", 30, 6 },
{ "July", "Jul", 31, 7 },
{ "August", "Aug", 31, 8 },
{ "September", "Sep", 30, 9 },
{ "October", "Oct", 31, 10 },
{ "November", "Nov", 30, 11 },
{ "December", "Dec", 31, 12 }
};
if(bLeap){
months[1].iDays ;
}
return months;
}
問題是,如果我在某個函式中形成一個INPUT結構:
INPUT GetUserInput(void){
// init months
MONTH * pMonths;
pMonths = init_months(isLeap(sDate.iYear));
// some code here
...
INPUT sInput = { pMonths, sDate, sCalcs };
// return
return sInput;
}
那么如何正確初始化MONTH陣列和/或如何正確初始化INPUT以便它在從GetUserInput()回傳時包含有效資料?
uj5u.com熱心網友回復:
您有 3 個選擇:
- 使其成為靜態(但所有回傳的參考都將參考相同的陣列)。
static MONTH months[NUM_MONTHS] = {
- 使用 malloc 和復合字面量
MONTH *months = malloc(sizeof(*months) * NUM_MONTHS);
/* check if memory was allocated */
memcpy(months, (MONTH[]){
{ .cName = "January", .cAbbr = "Jan", .iDays = 31, .iNumber = 1 },
{ "February", "Feb", 28, 2 },
{ "March", "Mar", 31, 3 },
{ "April", "Apr", 30, 4 },
{ "May", "May", 31, 5 },
{ "June", "Jun", 30, 6 },
{ "July", "Jul", 31, 7 },
{ "August", "Aug", 31, 8 },
{ "September", "Sep", 30, 9 },
{ "October", "Oct", 31, 10 },
{ "November", "Nov", 30, 11 },
{ "December", "Dec", 31, 12 }}, sizeof(*months) * NUM_MONTHS);
- 將表包裝成另一個結構并按值回傳
typedef struct
{
MONTH months[NUM_MONTHS];
}YEAR;
YEAR init_months(bool bLeap) {
YEAR year = {{
{ .cName = "January", .cAbbr = "Jan", .iDays = 31, .iNumber = 1 },
{ "February", "Feb", 28, 2 },
{ "March", "Mar", 31, 3 },
{ "April", "Apr", 30, 4 },
{ "May", "May", 31, 5 },
{ "June", "Jun", 30, 6 },
{ "July", "Jul", 31, 7 },
{ "August", "Aug", 31, 8 },
{ "September", "Sep", 30, 9 },
{ "October", "Oct", 31, 10 },
{ "November", "Nov", 30, 11 },
{ "December", "Dec", 31, 12 }}};
if(bLeap){
year.months[1].iDays ;
}
return year;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/393260.html
