DEV Community

221910302026
221910302026

Posted on

STRUCTURES AND UNIONS

Structures

A structure is a user-defined data type in C and C++. with this structure, we can combine different data types. It helps us to create complex data type which can be easily understandable and much more meaningful. Basically, we can group different data types into a single data type by using structure. In structure, we can store data in the form of records.

Using structure in a program

 We can define the structure in a C or C++ program by using the command struct.

 Example syntax for structure is 
struct address
{
char name[100];
int roll_no[100];
float marks[100];
};

 Structure cannot be initialized if there is a declaration. For example.
struct address
{
   int x = 1; // COMPILER ERROR: cannot initialize members here
   int y = 0; // COMPILER ERROR: cannot initialize members here
};
 
When a data type is declared, no memory is allocated for it. Memory is allocated when variables are created.

 We can also declare arrays in structure

 We can also declare a pointer in a structure.
An example of this is 

struct person per;
struct person *ptrA
ptrA=&per

In the first two lines, we are declaring a structure pointer, and in the last line, we are initializing it.

Unions

Union is a user-defined data type in C language. In the same memory location, it can store different data types. It provides an efficient way of using the same memory location for multiple purposes. It is kind of similar to a structure, but there are differences between structure and unions. In C, we use unions to save memory. In unions, only one member can contain the value.

Using union in a program

l we can define union in a program by using the command union

l The example syntax for union is 
union [union name]
{
Data type variable;
Data type variable;

Data type variable;
};

l We can create an array of the union just like an array of structures. For example
union example
{
char name[10];
int roll no[10];
};

l We can have pointers to unions just like structures.
union number n;
Union number *ptr=&n;

In the first line,n is the variable to number. In the second line, ptr is the pointer to the union, and it is assigning with the address of the union variable n.

Some differences between structures and unions

Structure
1) It can access individual members at a time
2) Each member within a structure is assigned a unique storage area of location.
Union
1) It can access only one member at a time
2) Memory allocated is shared by individual members of the union.

Top comments (0)