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

Now using structure pointer dp I want to access member of structure time sec.How do I do it?

1
  • 1
    Did you intend to have a member of type struct time in struct date? If so, you didn't name it, and what you have written doesn't compile. Commented Dec 17, 2016 at 7:17

2 Answers 2

1

You need to create a member of type struct time in struct date before you can access the sec member of the struct time from an object of type struct date.

You may elect not to name the nested struct but you need a member.

#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.
}
Sign up to request clarification or add additional context in comments.

Comments

0

Nested structure is basically a structure within a structure. In your example, struct time is a member of struct date. The logic for accessing member of a structure will remain the same. i.e.the way you access member day of struct date.

but here you will require to create structure variable for struct time in order to access its members.

If you want to access members of nested structure then it will look like,

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

You can check following code,

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


}

Output :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.