[英]Using structure in structure..unable ot access inner structure elements?
嗨朋友我是新手並且正在嘗試學習結構...這里我已經在結構計算中聲明了結構日期...但是沒有了解如何從日期訪問元素。 我已經通過使用malloc作為父結構calc ...來保留內存,這對於日期結構也是如此? 。請指導我...謝謝!
#include <stdio.h>
#include <stdlib.h>
struct date{
int day;
int month;
int year;
};
struct calc{
int row;
int col;
char menu_name[20];
char sub_menu_name[20];
struct date dob;
};
int main()
{
int count = 0, i;
struct calc *my_calc[2];
//here unable to understand that where i need to resever seprate memory for date?
my_calc[0] = (struct calc *)malloc(sizeof(struct calc));
//trying to asign the date value
for(count; count<2; count++)
{
printf("Please enter day: ");
scanf("%d",&my_calc[count]->date.day);
printf("Please enter month: ");
scanf("%d",&my_calc[count]->date.month);
printf("Please enter Year: ");
scanf("%d",&my_calc[count]->date.year);
}
//trying to print the date value
printf("Day: %d\t Month: %d\t Year: %d\n ",my_calc[0]->date.day,my_calc[0]->date.month,my_calc[0]->date.year);
system("PAUSE");
return 0;
}
你宣布dob
不是date
。 &my_calc[count]->dob.day
您需要使用dob
,而不是date
,例如:
scanf("%d",&my_calc[count]->dob.day);
要訪問的元素的名稱是dob
- date
是結構名稱。
通過此修改,您的代碼編譯良好,但您將遇到一些嚴重的運行時問題 - 請參閱有關如何正確分配內存的提示的其他答案。
如果你是malloc sizeof(struct calc)
那么它包括那個結構的所有元素(讀取:它對結構的所有元素執行sizeof
並將其相加並根據空間分配空間)。
我還在代碼中看到了很多指針/數組問題,你應該真正閱讀這個主題。
你需要通過元素dob
的名稱來引用,而不是元素的strcut名稱( date
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.