Home » C and C++, Tech Corner

Structures and Unions

31 August 2009 2 Comments Posted By:Dileep
  • An array is used to store and process a group of homogeneous elements. But, to store and process eleents that are not homogeneous, the knowledge of the structure is required. Structures help in packing the disimilar data items under a single name.
  • A structure is a meaningful collection of data items of different type. But it collects all elements under a unique name. A structure allows the programmer to create and manipulate a set of different types of data items.
  • The keyword struct.
  • Each and every structure must be defined and declared before it appear in a C program.
  • The body of the structure is terminated by a semicolon.

struct employee
{
int emp_code;
char name[20];
float salary;
};

  • The general form of declaring structure variables is :

structure_type varlist;

  • A structure within another structure is called an embedded structure.
  • A structure may completely be defined within the other structure.
  • There may be separate strucutres.The embedded structure is declared first and the other structure is declared next.

  • Like initialization of array elements, structure members can be initialized.
  • Each member of a structure is accessed with the dot operator.
  • The dot operator has the highest priority than any other operator of C, and it’s associativity is from left to right.
  • Whenever the same structure is to be applied to a group of people, items or applications we will have to use an array of structures.
  • typedef(for type definition) statement – enables the programmer to define an alternate term to the basic data types.

Syntax – typedef old_data_type new_data_type;

  • A union is a collection of heterogeneous data elements. They are similar to structures.
  • However, there is a difference in the way the structure members and union members are stored. Each member within a structure is asigned its own memory location. But the union members, all share a common memory location. Thus, unions are used to save memory.
  • An inividual member of a union can be accessed using the dot operator or ->(arrow) operator.

<<Previous Post

Next Post>>

Related posts:

  1. Arrays
  2. Pointers
  3. Constants and Variables
  4. Strings(Character Arays)
  5. Loop Control Structures(Decision Making & Looping)

2 Comments »

  • George said:

    Dileep…..
    It will be much better by providing some examples…..

  • Lloyd said:

    yes..will..do..that….

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>