This blog is under construction

Sunday, 13 May 2012

Structure within structure in C

A structure nested inside another structure is called structure within structure.

Method1:
struct velocity {
     char name[100];
     int distance;
     struct time_taken {
               int hours;
               int minutes;
               int seconds;
     } tobj;
} vobj;



Method 2:
struct time_taken {
          int hours;
          int minutes;
          int seconds;
};

struct velocity {
          char name[100];
          int distance;
          struct time_taken tobj;
}vobj;

Ways to access data members of the inner structure:
vobj.tobj.hours = 12
vobj.tobj.minutes = 30


Nested structure example in C:

  #include <stdio.h>
  struct time_taken {
        int hours;
        int minutes;
        int seconds;
  };

  struct velocity {
        char name[100];
        int distance;
        struct time_taken tm;
  };

  int main() {
        struct velocity v1 = {"ram", 7200, {10, 0, 0}};
        int velocity_op;
        int time = (((v1.tm.hours) * 3600) +
                        ((v1.tm.minutes) * 60) + (v1.tm.seconds));
        velocity_op = (v1.distance * 1000) / time;
        printf("Velocity:%dm/sec\n", velocity_op);
        return 0;
 }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Velocity:200m/sec



No comments:

Post a Comment