2013-03-13 115 views
0

嗨,朋友,我是新的,並試圖學習結構...在這裏我已經聲明結構日期結構calc ...但沒有得到想法如何從日期訪問元素。我已經使用malloc保留了內存,用於父結構calc..will,這對於日期結構來說足夠了嗎? 。請引導我...謝謝!在結構中使用結構..不能訪問內部結構元素?

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

回答

1

您聲明dob而不是date&my_calc[count]->dob.day

+0

非常感謝,我真的很愚蠢成爲...我會確保這將不會重複...對不起......坦克。 – studyembedded 2013-03-13 11:08:51

1

您需要使用dob,不date,例如:

scanf("%d",&my_calc[count]->dob.day); 

您要訪問的元素的名稱爲dob - date是結構名稱。

通過此修改,您的代碼編譯良好,但您將遇到一些嚴重的運行時問題 - 有關如何正確分配內存的提示,請參閱其他答案。

0

如果你malloc sizeof(struct calc)那麼包括該結構的所有元素(閱讀:它爲結構的所有元素和總結,並分配空間的總和做一個sizeof)。

我還在代碼中看到很多指針/數組問題,你應該真正閱讀這個主題。

而你需要通過元素dob的名稱爲ref,不命名strcut的因素是(date