Coupon Accepted Successfully!


Structure In C

In C, it is possible to combine dissimilar data types using structure but it has the following limitations:

  1. Functions are not allowed as members of structure.
  2. Direct access to data members is possible. So, by default all the structure members are public. Hence, security to data or data hiding is not provided.
  3. The struct data type is not treated as built-in type; that is the use of struct keyword is necessary to declare objects.
  4. The data members cannot be initialized inside the structure.

The syntax of structure declaration is as follows:


In the above example, item is a structure name. The data members are codeno, prize, and qty. Thus, a custom data type is created by combination of one or more data members.


The object of structure item can be declared as follows:


struct item a,*b

The object declaration is same as the declaration of variables of built-in data types. The object a and the pointer *b are variables of type item and each of them has three data members. The a and *b can access the data members of struct item. Use of keyword struct is necessary.

Access to structure members: The data members of a structure are accessed by using object name and operators such as dot (.) or arrow (->). The dot (.) or arrow (->) operators are known as referencing operators. The dot operator is used when simple object is declared and arrow operator is used when object is pointer to structure. The access of members can be accomplished as given in the following syntax:

[Object name][Operator][Member variable name]


When an object is a simple variable, access of members is done as follows:


Object name dot(.) member variable name




When an object is a pointer to structure then members are accessed as follows:





Note: A structure declaration must have a name or identifier followed by keyword struct, else the compiler will display an error. This is because it will not recognize the type of object declared. Hence, there is no possibility of accessing the structure member variables.


The following program illustrates the above discussion.

8.1 Write a program to access data members of a structure.

Explanation: The above program is compiled with C compiler. The following discussion is according to C compiler. In the above program, the structure item is declared with three member variables. The initialization of member variables inside the struct is not permitted. The declaration of member variables is enclosed within the curly braces. The struct declaration is terminated with a semicolon.

In function main(), the objects a and b are declared. Consider the following statement.

struct item a,*b; // object declaration

The struct must be preceded by structure name. The member variables can be accessed and initialization is done directly by object. The dot and arrow operators are used to access the member variables.

Test Your Skills Now!
Take a Quiz now
Reviewer Name