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



1 comment:

  1. Dell Laptop Service center are giving repair service at the door. We should high quality Dell out of warranty Laptop Repair, removal of virus, screen removal, wireless network set up, battery removal, motherboard replacement to several other are offered at budget friendly price and it’s Negotiable. We can fix them all in time by our well experience and certified technicians. If you want to repair your laptop in front of your eyesight, than you may call us: 7217871051

    ReplyDelete