A structure is a user-defined data type containing a collection of logically related data which may be of different types such as int, double, char, and so on. All of them are encapsulated (packed) in a single unit with a single name. The classes of C++ are in fact generalization of C-structures. A class in C++ with only public members is similar to a C-structure. All members of a structure in C are by default public. However, in a class declaration in C++, if there is no access specifier, the members are private by default. We know that arrays can be used to represent a group of data items that belong to the same type, such as int or float. This restriction is not there in structures.
Consider the examples given below:
1. Process the information of a library book (accession number, title, author, publisher, price, purchase date, issue status, etc.)
2. Process the information of a student (roll number, name, date of birth, e-mail address, marks in several subjects, result, percentage marks, etc.)
3. Process the information of an inventory item (item code, name, price, quantity, etc.)
However we cannot use an array if we want to represent a collection of data items of different types using a single name. A structure is a convenient tool for handling a group of logically related data items.
We’ll be covering the following topics in this tutorial:
Declaring Structures
To use a structure in our program, we have to first declare it. The general format for the declaration of a structure is given below.
struct structure_name { type element 1; type element 2; type element n; };
In structure declaration the keyword struct appears first is a C keyword, this followed by structure_name is the name of the structure being declared. The rules for naming a structure tag are the same as those for a variable name. We can define multiple structures within a scope. However, each of them must have a distinct name. The member of structure should be enclosed between a pair of braces and it defines one by one each ending with a semicolon. The variables declared within the curly braces in the above declaration are called the members, fields or components of a structure. It can also be array of structure. There is an enclosing brace at the end of declaration and it end with a semicolon.
As mentioned earlier, the members ofstructure may be of the same or different types. Thus, the member-declarations may consist of one or more declaration statements each of which takes the usual form:
We can declare structure variables as follows
struct structure_name var1,var2,....,var n;
For Example: To store the names, roll number and total mark of a student you can declare 3 variables. To store this data for more than one student 3 separate arrays may be declared. Another choice is to make a structure. No memory is allocated when a structure is declared. It just defines the “form” of the structure. When a variable is made then memory is allocated. This is equivalent to saying that there’s no memory for “int” , but when we declare an integer that is. int var; only then memory is allocated. The structure for the above-mentioned case will look like
struct student { int rollno; char name[25]; float totalmark; };
We can now declare structure variables stud1, stud2 as follows struct student stud1,stud2; Thus, the stud1 and stud2 are structure variables of type student. The above structure can hold information of 2 students. It is possible to combine the declaration of structure combination with that of the structure variables, as shown below.
The following single declaration is equivalent to the two declaration presented in the previous example.
struct student { int rollno; char name[25]; float totalmark; } stud1, stud2;
The different variable types stored in a structure are called its members. The structure member can be accessed by using a dot (.) operator, so the dot operator is known as structure member operator.
Example: In the above example stud1 is a structure variable of type student. To access the member name, we would write stud1.name Similarly, stud1’s rollno and stud1’s totalmark can be accessed by writing stud1.rollno And stud1.totalmark
Defining Structure Variables
The declaration of a structure only lists its members along with their types. It does not allocate any memory for member variables. The structure name is thus similar to a data type. Memory is allocated only when we define variables of this structure type.
Once a structure is declared, we can define variables of that type using the. Following syntax:
struct tag var_list ;
where tag is the structure name and var_list is a comma-separated list of variable names. A structure variable name must be distinct within a scope. Thus, it cannot be the same as that of any other variable in that scope. However, it can the be same as that of a structure tag.
For example, we can declare variables d and today of type struct date just declared as follows:
struct date d, today;
Now both the variables d and today have three members, namely, dd,mm and yy of type int.
We can also define variables at the end of a structure declaration, between the closing brace and the semicolon, using the format given below.
struct tag { member declarations ; } var_list;
Thus, we can declare a structure to represent complex numbers and also define variables x and y as complex numbers using the declaration given below.
struct complex { float re, im; } x, y;
In this case, variables x and y are of type struct complex and each of them has two members re and im of type float.
Note that it is also possible to omit the structure name in a structure declaration. Such structures are called anonymous structures. This is particularly useful when we want to declare all the required variables of this structure type in this anonymous structure declaration and do not have to use the structure name in the subsequent program (e. g. to pass or return values to and from a function). Thus, the above declaration can also be written as shown below.
struct { float re, im; } x, y;
Finally, note that we can declare scalar variables as well as arrays of structure types.
Accessing Structure Members – the Dot Operator
Each structure variable has member variables as specified in the declaration of the corresponding structure. To access the individual members of a structure variable, C language provides the structure member operator (.), which is also called as the dot operator. A member of a structure variable can be accessed by writing the structure variable name followed by the dot operator and the name of desired member as shown below.
struct-var.member-name
Thus, the members of variable today of type struct date, declared in the previous section, can be accessed as today.dd, today.mm and today.yy. Note that we can use a structure member only in conjunction with a structure variable. Using a structure member on its own is an error that beginners should avoid. For example, using dd, mm and yy without the name of the structure variable is an error.
Once we access a structure member as shown above, we can perform various operations on it, e. g., we can use it in an expression, assign a value to it, pass it as an argument to a function and so on. Note that the dot operator has higher precedence than most other operators. Thus, when we access a structure member within an expression, we do not need to enclose it within parentheses.
To increment (decrement) a value of a structure member, we can use either the prefix or postfix increment (decrement) operator as follows:
++ struct var. member name struct var. member name ++ -- struct var .member name struct-var. member-name --
Note that in these expressions, the dot operator is bound first to its operands followed by the ++ (–) operator. Thus, the increment (decrement) operator operates on the member variable and not the structure variable.
We often require the address of a member variable, e. g., to read its value using the scanf function. We can obtain it using the address-of operator(&) as shown below.
struct_var.member_name
In this case, the dot operator is correctly bound to its operands first followed by the address of operator. Thus, the address-of operator gives us the address of the member variable and not the structure variable.
Structure Initialization
The C language allows initialization of a structure variable, the syntax for which is similar to the initialization of an array as shown below:
struct tag var= { expr1, expr2, ... } ;
where tag is the name of the structure already defined and var is a variable of type struct tag. The initializer is a comma-separated list of expressions of appropriate type enclosed in curly braces. The first member of structure variable var is initialized with the value of exprl, the second member is initialized with expr2 and so on. The type of each expression must be in accordance with the corresponding member variable; otherwise, conversions are applied to convert its value to the desired type. However, if such a conversion is not possible, the compiler will report an error.
It is not necessary to initialize all members of a structure variable. If we specify fewer values than required, the remaining members are initialized with the default value, which is zero for arithmetic variables and NULL for pointer variables. However, if we specify more values than required, the compiler will issue an error message.
Although we can initialize multiple variables in a single initialization statement as shown below, it is better to initialize only one variable at a time.
struct tag var1 = { expr, expr, } , var2 = { expr, expr , } , ... ;
We can combine structure declaration and initialization of structure variables as shown below.
struct tag { member-declarations; var1 = { expr, expr, } , var2 = { expr, expr, } ,
Further, we can mix the definition and initialization of structure variables. Thus, in the statement given below, three variables are defined but only one is initialized. However, it is better to avoid such code as it affects program readability.
struct tag var1, var2 = { exprl, expr2, ... } , var3 ;
We can also initialize a structure variable using variables of same type as shown below.
struct tag var1 = var2 ;
Finally, note that we cannot initialize the members of a structure in its definition. Thus, the following format is incorrect.
/* incorrect format for initialization of a structure */ struct tag { type1 var1 = expr1; /*wrong*/ type2 var2 = expr2; /*wrong*/ ...... }
Structure Assignment
To copy (or assign) an entire structure variable to another of the same type, we need to copy the values of member variables one at a time. However, there is a simpler way to do this. The C language allows a structure variable to be assigned to another variable of the same type using an assignment of the form
var1 = var2;
This statement assigns the value of each member of structure variable var2 to the corresponding member of variable var 1. Thus, the code given below first initializes a complex number a and then assigns it to another complex variable b:
struct complex { float re, im; } a= {3, 4}; struct complex b; b = a;
Illustrates structures initialized by user
#include<stdio.h> struct Grades { char Name[30]; char Roll_Number[12]; float Grade; int Rank; } ; void main () { struct Grades S1 = {"Madhu", "2009physll2", 78.5, 12}; struct Grades S2, S3; clrscr(); printf("Enter the data of S2\n"); scanf("%s %s %f %d",S2.Name,S2.Roll_Number, S2.Grade, S2.Rank); printf("Enter the data of S3\n"); scanf("%s %s %f %d",S3.Name,S3.Roll_Number, S3.Grade, S3.Rank); printf("Name \t Roll_Number\t Grades \t Rank\n"); printf("%s\t%s\t%f\t%d\n",S1.Name,S1.Roll_Number,S1.Grade,S1.Rank); printf("%s\t%s\t%f\t%d\n",S2.Name,S2.Roll_Number,S2.Grade,S2.Rank); printf("%s\t%s\t%f\t%d\n",S3.Name,S3.Roll_Number,S3.Grade,S3.Rank); }