2016-12-17 134 views
1
#include<stdio.h> 
struct date 
{ 
     struct time 
     { 
       int sec; 
       int min; 
       int hrs; 
     }; 
     int day; 
     int month; 
     int year; 
    }; 
int main(void) 
{ 
    stuct date d,*dp=NULL; 
    dp=&d; 
} 

現在使用結構指針dp我想訪問結構時間秒的成員。我該怎麼做?如何使用指針訪問嵌套結構的成員?

+1

你打算在'struct date'中有'struct time'類型的成員?如果是這樣,你沒有命名它,你寫的東西不能編譯。 – e0k

回答

1

您需要struct date創建struct time類型的成員,才能從struct date類型的對象訪問struct timesec成員。

您可以選擇不命名嵌套的struct,但您需要一個成員。

#include <stdio.h> 

struct date 
{ 
    // struct time { ... } time; or 
    // struct { ... } time; 
    // struct time 
    struct 
    { 
     int sec; 
     int min; 
     int hrs; 
    } time; // Name the member of date. 
    int day; 
    int month; 
    int year; 
}; 

int main(void) 
{ 
    struct date d,*dp=NULL; 
    dp=&d; 

    dp->time.sec = 10; // Access the sec member 
    d.time.min = 20; // Accces the min member. 
} 
0

嵌套結構基本上是一個結構內的結構。在你的例子中,struct timestruct date的成員。 訪問結構成員的邏輯將保持不變。即您訪問struct date的會員day的方式。

但在這裏您需要創建struct time的結構變量才能訪問其成員。

如果您想訪問嵌套結構的成員,然後它看起來像,

dp->time.sec // dp is a ptr to a struct date 
d.time.sec // d is structure variable of struct date 

您可以檢查下面的代碼,

#include<stdio.h> 
struct date 
{ 
     struct time 
     { 
       int sec; 
       int min; 
       int hrs; 
     }time; 
     int day; 
     int month; 
     int year; 
}; 

int main(void) 
{ 
    struct date d = {1,2,3,4,5,6}, *dp; 

    dp = &d; 

    printf(" sec=%d\n min=%d\n hrs=%d\n day=%d\n month=%d\n year=%d\n",dp->time.sec, dp->time.min, dp->time.hrs, dp->day, dp->month, dp->year); 


} 

輸出:

sec=1 
min=2 
hrs=3 
day=4 
month=5 
year=6