This blog is under construction

Sunday, 13 May 2012

Structure initialization in C

Assigning initial values to the structure variables is called structure initialization and these initialized values can be altered during the program execution.

Let us see all possible ways to initialize members of a structure variable.

Method 1:
struct student {
     char name[100];
     int age;
};
struct student obj = {"Jackson, 10};
Here, initialization is done after structure definition.  "Jackson" is assigned to the member name of structure variable obj and 10 is assigned to the member age of structure variable obj.

Method 2:
struct student {
     char name[100];
     int age;
}obj = {"Jackson", 10};

Here, initialization is done during the time of structure definition itself.  "Jackson" is assigned to the member name of structure variable obj and 10 is assigned to the member age of structure variable obj.

Method 3:
struct student {
     char name[100];
     int age;
};
struct student obj = {.name = "Jackson", .age = 10};
Here, initialization is done after structure definition.  And we have used dot(.) operator for initialization.

Method 4:
struct student {
     char name[100];
     int age;
};
struct student obj = {name : "Jackson", age : 10};
This method is similar to method 3.  Here, color(:) is used instead of '=' and period before structure member is removed

Method 5:
struct student {
     char name[100];
     int x, *ptr;
     float y;
};
struct student obj = {"Jackson"};
Here, we have done partial initialization for structure variable.  So, "Jackson" will be assigned to member name of structure variable obj.  Whereas, the other members of the structure variable obj are initialized to default values.  (x is initialized to 0, ptr is initialized to NULL and y is initialized to 0.0).


Example:

  #include <stdio.h> 
  /* structure definition */
  struct student {
        char name[32];
        int age;
  }obj1 = {"Tom", 10};  // initialization

  /* prints the value of members of given structure variable */
  void print(struct student obj) {
        printf("Age of %s is %d\n", obj.name, obj.age);
        return;
  }

  int main() {
        /* initializing strucuture variable */
        struct student obj2 = {"Jerry", 10};
        struct student obj3 = {.name="Yang", .age=10};
        struct student obj4 = {name:"Bruce", age:11};
        struct student obj5 = {"Lee"};
        print(obj1);  // printing values of structure variable obj1
        print(obj2);  // printing values of structure variable obj2
        print(obj3);  // printing values of structure variable obj3
        print(obj4);  // printing values of structure variable obj4
        print(obj5);  // printing values of structure variable obj5
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Age of Tom is 10
  Age of Jerry is 10
  Age of Yang is 10
  Age of Bruce is 11
  Age of Lee is 0



No comments:

Post a Comment