This blog is under construction

Sunday 13 May 2012

Structure definition and declaration in C

Below is the general definition of a structure

struct structure_name{
              type variable1;
              type variable2;
              ---------------
};

struct                       -  keyword
structure_name        -  tag
type                         - data type
variable1, variable2  -  data members of the given structure

Consider the following example,
struct student {
        int age;
        char name[32];
};
Above is a definition of a structure named struct student.

Let us see how to declare structure variables.  Structure variables can be declared while defining a structure or after structure definition.

Declaring structure variables at structure definition
struct student {
          int age;
          char name[32];
}obj1, obj2;

Here, obj1 and obj2 are structure variables of type struct student.  And they are declared during structure definition.

Declaring structure variables after structure definition:
struct student {
          int age;
          char name[32];
};
struct student obj1, obj2;

Here, obj1 and obj2 are structure variables of type struct student.  And they are declared after structure definition.

Example:

  #include <stdio.h> 
  struct student {
        char name[100];
        int rank;
  }obj = {"jp", 1};

  int main() {
        // struct student obj = {"jp", 1};
        printf("Name: %s\n", obj.name);
        printf("Rank: %d\n", obj.rank);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Name: jp
  Rank:1


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