Tuesday, August 23, 2011

C Programming: Structures

We know that array is a collection of data that represent same data type. We cannot make array that has data with different types using a single name. Fortunately, C supports a constructed data type called structures a mechanism for packing data of different types. A structure is a convenient tool for handling a group of logically related data items. For example, it can be used to represent a set of attributes, such as student_name, roll_number and marks. The concept of a structure is analogous to that of a ‘record’ in many other languages.

Defining a structure

Unlike arrays, structures must be defined first for their format they may be used later to declare structure variable. structure definition is the template of structure variable. The general format of a structure definition is

struct tag_name
data_type member1;
data_type member 2;
- - - - - - - - -
Declaring structure variable
After defining a structure format you can declare variables of that type. A structure variable declaration is similar to the declaration of variable of any other types. It includes the following elements:

  • The keyword struct

  • The structure tag name

  • List of variable names separated by commas.

  • A terminating semicolon
The general syntax is 
struct tag_name variable1, variable2, variable3,...,variableN;

  1: struct student{
  2:    char name[10];
  3:    int roll_no;
  4:    float marks;
  5: };
  7: struct student student1;

In this example line numbers 1-5 is structure definition. A structure is defined with tag_name student having members name, roll_no and marks. This is only template for structure variable. Remember members themselves are not variables. They do no occupy any memory until they are associated with the structure variables such as student1 in above example. Till line 7 no variable is created and structure definition cannot do anything without variable. Line 7 declares a structure variable student1 which has fields name, roll_no and marks. If you declare another variable like student2 then it also includes those fields(members). 

Accessing structure members

We can access and assign values to the members of a structure in a number of ways. As mentioned earlier, the members themselves are not variables. They should be linked to the structure variables in order to make them meaningful members. The link between a member and a variable is established using the member operator ‘.’which is also known as ‘dot operator’ or ‘period operator’. For example, student1.marks is the variable representing the marks of student1 and can be treated like any other ordinary variables.

No comments:

Post a Comment