Structures in C Language Tutorial Notes Study Material with Examples
Structures
Structures in C are used to encapsulate or group together different data into one object. We can define a structure as given below
struct object
{
char id [20];
int rollno;
int marks;
};
The variables we declare inside the structure are called data member.
Initializing a Structure
Structure members can be initialized when we declare a variable of our structure.
Sample Code
struct object student1= {“Ram”, 1, 95};
The above declaration will create a struct object called student1 with an id equal to “Ram”, rollno equal to 1 and marks equal to 95. To access the
members of a structure, we use the “.” (dot operator) i.e., scope resolution operator.
struct object student1;
student1 . id = “Ram”
student1. roll no = 1 ;
student1. marks = 95;
Key Points
- The values of a structure variable can be assigned to another structure variable of the same type using assignment operator.
- One structure can be nested within another structure. Using this facility, complex data types can be created.
e.g., struct emp
{
char name [100];
struct Address a;
);
- A structure variable can also be passed to a function. We may either pass individual structure elements or the entire structure variable at one go .
- We can have a pointer pointing to a struct. Such pointers are known as structure pointers.
Unions
A union is a collection of heterogeneous elements that is, it is a group of elements which are having different data types. Each member within a structure is assigned its own memory location. But the union members, all share a common memory location. Thus, unions are used to save memory.
union person
{
char name [20]; // Union definition
int age;
float height;
}
Like structures, unions are also defined and declared.
union person Ram; // Union declaration
Importance of Turing Machine Tutorial Notes Study Material with Examples
Follow Us on Social Platforms to get Updated : twiter, facebook, Google Plus
Learn Turing Machine in Handbook Series: Click here