structures and union in c programming

 Structures in c...



  • In A structure can be considered as a template used for defining a collection of variables under a single name. 
  • Structures help  of programmers to group elements of different datatypes into a single logical unit (Unlike arrays which permit a programmer to group only elements of same data type).  


        Let we want to store a date inside a C program. Then, we can define a structure called date with              three elements n1, n2 and n3. The syntax of this structure is as follows:

    struct date
    {
       int n1;
       int n2;
       int n3;
    };

  • A structure type is usually defined at the beginning of a program. 
  • This usually occurs just after the main() statement in a file. 
  • Then a variable of this structure type is declared and used in the program. 

   For example:



         struct date order_date;

         important;  When you are first define a structure in a file, the statement simply tells the C                    compiler that a structure exists, but causes no memory allocation. Only when a structure                      variable is declared, memory allocation takes place.

Initializing Structures



  • Unlike standard variables, the syntax for initialising structure variables is different.
  • The structure elements are accessed using the dot notation.
  •  The individual elements are initialised as follows :


         order_date.day = 9;
         order_date.month = 12;
          order_date.year = 1995;
          One can either initialize a structure by initializing the individual elements as shown above or                by simply listing the element's value inside curly braces, with each value separated by a                      comma.

       static struct date order_date = {9,12,1995};

         Similar to initialization of arrays, partial initialization of a structure can be done as follows :

         static struct date order_date = {9,12};

             In the above case the year element is initialised to zero.


Using Typedef keyword



  • In C language allows a programmer to rename data types using the keyword typedef.For example:


                 typedef unsigned int Uint;
                  Uint EmpID;
           you have typedefined a unsigned integer as Uint, you can then use Uint in your program as any            native data type, and declare other variables with its data type. You can similarly typedef a                  structure too.


              typedef struct point{
               float x;
               float y;
               } center_of_circle;
         you can use the newly defined data type, as in the following example:

             center_of_circle center1;
             center_of_circle center2;

Nested structures



  • here One can define a structure which in turn can contain another structure as one of its members.


             typedef struct circle_parameters{
             center_of_circle center;
             float radius;
              } circle;
             circle c1;


  •    The definition of a circle structure requires that a center_of_circle structure be previously defined to the compiler, or a compiler error is generated.


  • To access a particular member inside the nested structure requires the usage of the dot notation.


                    c1.center.x = 10;

        in here,  This statement sets the x value of the center of the circle to 10.

Arrays of structures



  • C does not limit a programmer to storing simple data types inside an array. 
  • User defined structures too can be elements of an array.


            struct date birthdays[10];

  • In  This defines an array called birthdays that has 10 elements.
  •  Each element inside the array will be of type struct date. 
  •  


      birthdays[1].month = 09;
      birthdays[1].day = 20;
      birthdays[1].year = 1965;


  • Initialisation of structure arrays is similar to initialization of multidimensional arrays :


                static struct birthdays[10] = {{9,30,1965},{9,26,1971}};
               initialise the first two elements of the birthdays array.

Structures containing arrays



  • There can also be structures containing arrays as its elements
  • . Do not confuse this concept with array of structures.


                  struct car{
                 char name[5];
                  int model_number;
                 float price;
                     };

  • This sets up a structure with a name car which has an integer member variable model_number, a float member variable price and a character array member called name,
  • . The character array member has an array of 5 characters.



  •   define a variable of type struct car.


             struct car car1;

           and initialize its values:

           static struct car car1 = {{'h','o','n','d','a'},1990,10000};

           here, above statement indicates the syntax to be used when initializing a structure containing               an array.

Structures and Pointers



  •  it like a variable, you can declare a pointer pointing to a structure and assign the beginning address of a structure to it. 
  • In The following piece of code will help understand this concept.


               typedef struct {
              int account_num;
              char account_type;
             char f_name[40];
             char l_name[40];
             float balance;
             } account;
         a pointer can be define as pointing to a variable, as follows:

             account acct1, *pt1;       pt1 = &acct1;


  •   the character "*" is used in front of pt1 to specify that pt1 is a pointer, and the character "&" is used in front of acct1 to pass its address to pt1 rather than its value.



  • Another important concept one must learn is the usage of the -> operator in conjunction with a pointer variable pointing to a structure.


UNIONS  in c...



  • A union is a variable which may hold members of different sizes and types. 
  • The syntax for declaring a union is similar to that of a structure:


           union number{
           int number;
           double floatnumber;
              } anumber;

  • This defines a union called "number" and a variable of it called "anumber".
  •  Here, number is the name of the union, and acts in the same way as a tag for a structure.


        Members of the union can be accessed in the following way:

              printf("%f",anumber.floatnumber);


  • important : When the C compiler is allocating memory for unions it will always reserve enough room for the largest member. In the above example it is 8 bytes for the double.
  •  Whereas, if the above union was a structure, then the C compiler would have reserved 10 bytes which is the total sum of the size of the individual elements.


      example;

              #include <stdio.h>

               main ()
                {
               union id {
                char name[40];//char union
              int number;
                         };
               struct {
               int salary;
               union id description;//union
                } student,faculty;


           printf("%d\n", sizeof(union id));
           student.description.name ="Sam";
           printf("%s %d\n",
           student.description.name,student.description.number);
          student.description.number = 12;
           printf("%s %d\n",
           student.description.name,student.description.number);


              }


           in the above program the value 'Sam' is assigned to the union member                                                    student.description.name, so the first printf() statement -produces an output 40, which is the                  size of the union in bytes. The second and third printf() statements produce the following                    outputs respectively :

     Sam ---33000



  • Here, in the first line, the first value is meaningful, but the second one is not,similarly in the second line, the second value is meaningful. This clearly indicates that the union can contain any one value at any given time and not both.


No comments:

Post a Comment