0% found this document useful (0 votes)
12 views

C Structures

Uploaded by

namitmonteiro29
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

C Structures

Uploaded by

namitmonteiro29
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

C Structures

The structure in C is a user-defined data type that can be used to group items of
possibly different types into a single type. The struct keyword is used to define the
structure in the C programming language. The items in the structure are called
its member and they can be of any valid data type. Additionally, the values of a
structure are stored in contiguous memory locations.

C Structure Declaration
We have to declare structure in C before using it in our program. In structure
declaration, we specify its member variables along with their datatype. We can use
the struct keyword to declare the structure in C using the following syntax:
Syntax
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
The above syntax is also called a structure template or structure prototype and no
memory is allocated to the structure in the declaration.

C Structure Definition
To use structure in our program, we have to define its instance. We can do that by
creating variables of the structure type. We can define structure variables using
two methods:

1. Structure Variable Declaration with Structure Template


struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;

2. Structure Variable Declaration after Structure Template


// structure declared beforehand
struct structure_name variable1, variable2, .......;
Access Structure Members
We can access structure members by using the ( . ) dot operator.

Syntax
structure_name.member1;
strcuture_name.member2;

Initialize Structure Members


Structure members cannot be initialized with the declaration. For example, the
following C program fails in the compilation.
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
The reason for the above error is simple. When a datatype is declared, no memory
is allocated for it. Memory is allocated only when variables are created.

Default Initialization
By default, structure members are not automatically initialized to 0 or NULL.
Uninitialized structure members will contain garbage values. However, when a
structure variable is declared with an initializer, all members not explicitly initialized
are zero-initialized.
struct Point
{
int x;
int y;
};
struct Point p = {0}; // Both x and y are initialized to 0
We can initialize structure members in 3 ways which are as follows:
1. Using Assignment Operator.
2. Using Initializer List.
3. Using Designated Initializer List.
1. Initialization using Assignment Operator
struct structure_name str;
str.member1 = value1;
str.member2 = value2;
str.member3 = value3;
.
.

2. Initialization using Initializer List


struct structure_name str = { value1, value2, value3 };
In this type of initialization, the values are assigned in sequential order as they are
declared in the structure template.

3. Initialization using Designated Initializer List


Designated Initialization allows structure members to be initialized in any order.
struct structure_name str = { .member1 = value1, .member2 = value2, .member3
= value3 };

Example of Structure in C
The following C program shows how to use structures
/ C program to illustrate the use of structures
#include <stdio.h>
// declaring structure with name str1
struct str1 {
int i;
char c;
float f;
char s[30];
};
// declaring structure with name str2
struct str2 {
int ii;
char cc;
float ff;
} var; // variable declaration with structure template
// Driver code
int main()
{
// variable declaration after structure template, initialization with initializer list
and designated, initializer list
struct str1 var1 = { 1, 'A', 1.00, "c program" },
var2;
struct str2 var3 = { .ff = 5.00, .ii = 5, .cc = 'a' };
// copying structure using assignment operator
var2 = var1;
printf("Struct 1:\n\ti = %d, c = %c, f = %f, s = %s\n",
var1.i, var1.c, var1.f, var1.s);
printf("Struct 2:\n\ti = %d, c = %c, f = %f, s = %s\n",
var2.i, var2.c, var2.f, var2.s);
printf("Struct 3\n\ti = %d, c = %c, f = %f\n", var3.ii,
var3.cc, var3.ff);
return 0;
}
Output
Struct 1:
i = 1, c = A, f = 1.000000, s = c program
Struct 2:
i = 1, c = A, f = 1.000000, s =c program
Struct 3
i = 5, c = a, f = 5.000000
Uses of Structure in C
C structures are used for the following:
1. The structure can be used to define the custom data types that can be used
to create some complex data types such as dates, time, complex numbers,
etc. which are not present in the language.
2. It can also be used in data organization where a large amount of data can be
stored in different fields.
3. Structures are used to create data structures such as trees, linked lists, etc.
4. They can also be used for returning multiple values from a function.

Limitatins of C Structures
In C language, structures provide a method for packing together data of different
types. A Structure is a helpful tool to handle a group of logically related data items.
However, C structures also have some limitations.
• Higher Memory Consumption: It is due to structure padding.
• No Data Hiding: C Structures do not permit data hiding. Structure members
can be accessed by any function, anywhere in the scope of the structure.
• Functions inside Structure: C structures do not permit functions inside the
structure so we cannot provide the associated functions.
• Static Members: C Structure cannot have static members inside its body.
• Construction creation in Structure: Structures in C cannot have a
constructor inside Structures.

Array of Structures in C
When dealing with a large set of related data and different data types, organizing
and managing it efficiently is crucial. In C programming, the combination of arrays
and structures i.e. array of structures provides a powerful tool for managing that.
What is Array?
The array is a homogeneous collection of elements stored in the continuous
memory location. The size of the array is fixed and we can randomly access the
elements using their index.
Declaration of Array
array_type array_name[size];
What is Structure?
The structure is one of the user-defined data types in C that can contain elements
of different types as its members.

Declaration of a Structure in C
struct structure_name{
memberType memberName;
...
...
};

Array of Structures
An array whose elements are of type structure is called array of structure. It is
generally useful when we need multiple structure variables in our program.

Need for Array of Structures


Suppose we have 50 employees and we need to store the data of 50 employees. So
for that, we need to define 50 variables of struct Employee type and store the data
within that. However, declaring and handling the 50 variables is not an easy task.
Let’s imagine a bigger scenario, like 1000 employees.
So, if we declare the variable this way, it’s not possible to handle this.
struct Employee emp1, emp2, emp3, .. . ... . .. ... emp1000;
For that, we can define an array whose data type will be struct Employee soo that
will be easily manageable.

Declaration of Array of Structures


struct structure_name array_name [number_of_elements];

Initialization of Array of Structures


We can initialize the array of structures in the following ways:
struct structure_name array_name [number_of_elements] = {
{element1_value1, element1_value2, ....},
{element2_value1, element2_value2, ....},
......
......
};
The same initialization can also be done as:
struct structure_name array_name [number_of_elements] = {
element1_value1, element1_value2 ....,
element2_value1, element2_value2 .....
};
struct structure_name array_name [number_of_elements] = {
{.element3 = value, .element1 = value, ....},
{.element2 = value, .elementN = value, ....},
......
......
};

Example of Array of Structure in C


// C program to demonstrate the array of structures
#include <stdio.h>
// structure template
struct Employee {
char Name[20];
int employeeID;
int WeekAttendence[7];
};
// driver code
int main()
{
// defining array of structure of type Employee
struct Employee emp[5];
// adding data
for (int i = 0; i < 5; i++) {
emp[i].employeeID = i;
strcpy(emp[i].Name, "Amit");
int week;
for (week = 0; week < 7; week++) {
int attendence;
emp[i].WeekAttendence[week] = week;
}
}
printf("\n");
// printing data
for (int i = 0; i < 5; i++) {
printf("Emplyee ID: %d - Employee Name: %s\n",
emp[i].employeeID, emp[i].Name);
printf("Attendence\n");
int week;
for (week = 0; week < 7; week++) {
printf("%d ", emp[i].WeekAttendence[week]);
}
printf("\n");
}
return 0;
}

Output
Emplyee ID: 0 - Employee Name: Amit
Attendence
0123456
Emplyee ID: 1 - Employee Name: Amit
Attendence
0123456
Emplyee ID: 2 - Employee Name: Amit
Attendence
0123456
Emplyee ID: 3 - Employee Name: Amit
Attendence
0123456
Emplyee ID: 4 - Employee Name: Amit
Attendence
0123456

C Unions
The Union is a user-defined data type in C language that can contain elements of
the different data types just like structure. But unlike structures, all the members in
the C union are stored in the same memory location. Due to this, only one member
can store data at the given instance.

C Union Declaration
In this part, we only declare the template of the union, i.e., we only declare the
members’ names and data types along with the name of the union. No memory is
allocated to the union in the declaration.
union union_name {
datatype member1;
datatype member2;
...
};
Keep in mind that we have to always end the union declaration with a semi-colon.

Different Ways to Define a Union Variable


We need to define a variable of the union type to start using union members.
There are two methods using which we can define a union variable.
1. With Union Declaration
2. After Union Declaration
1. Defining Union Variable with Declaration
union union_name {
datatype member1;
datatype member2;
...
} var1, var2, ...;
2. Defining Union Variable after Declaration
union union_name var1, var2, var3...;
where union_name is the name of an already declared union.

Access Union Members


We can access the members of a union by using the ( . ) dot operator just like
structures.
var1.member1;
where var1 is the union variable and member1 is the member of the union.
The above method of accessing the members of the union also works for the
nested unions.
var1.member1.memberA;
Here,
• var1 is a union variable.
• member1 is a member of the union.
• memberA is a member of member1.

Initialization of Union in C
The initialization of a union is the initialization of its members by simply assigning
the value to it.
var1.member1 = some_value;
One important thing to note here is that only one member can contain some
value at a given instance of time.

Example of Union
// C Program to demonstrate how to use union
#include <stdio.h>
// union template or declaration
union un {
int member1;
char member2;
float member3;
};
// driver code
int main()
{
// defining a union variable
union un var1;
// initializing the union member
var1.member1 = 15;

printf("The value stored in member1 = %d",


var1.member1);

return 0;
}
Output
The value stored in member1 = 15

Size of Union
The size of the union will always be equal to the size of the largest member of the
array. All the less-sized elements can store the data in the same space without any
overflow.

Example 1: C program to find the size of the union


// C Program to find the size of the union
#include <stdio.h>
// declaring multiple unions
union test1 {
int x;
int y;
} Test1;
union test2 {
int x;
char y;
} Test2;
union test3 {
int arr[10];
char y;
} Test3;
// driver code
int main()
{
// finding size using sizeof() operator
int size1 = sizeof(Test1);
int size2 = sizeof(Test2);
int size3 = sizeof(Test3);
printf("Sizeof test1: %d\n", size1);
printf("Sizeof test2: %d\n", size2);
printf("Sizeof test3: %d", size3);
return 0;
}
Output
Sizeof test1: 4
Sizeof test2: 4
Sizeof test3: 40
Advantages of structure
Here are pros/benefits for using structure:
• Structures gather more than one piece of data about the same subject
together in the same place.
• It is helpful when you want to gather the data of similar data types and
parameters like first name, last name, etc.
• It is very easy to maintain as we can represent the whole record by using a
single name.
• In structure, we can pass complete set of records to any function using a
single parameter.
• You can use an array of structure to store more records with similar types.
Advantages of union
Here, are pros/benefits for using union:
• It occupies less memory compared to structure.
• When you use union, only the last variable can be directly accessed.
• Union is used when you have to use the same memory location for two or
more data members.
• It enables you to hold data of only one data member.
• Its allocated space is equal to maximum size of the data member.
Disadvantages of structure
Here are cons/drawbacks for using structure:
• If the complexity of IT project goes beyond the limit, it becomes hard to
manage.
• Change of one data structure in a code necessitates changes at many other
places. Therefore, the changes become hard to track.
• Structure is slower because it requires storage space for all the data.
• You can retrieve any member at a time in structure whereas you can access
one member at a time in the union.
• Structure occupies space for each and every member written in inner
parameters while union occupies space for a member having the highest
size written in inner parameters.
• Structure supports flexible array. Union does not support a flexible array.
Disadvantages of union
Here, are cons/drawbacks for using union:
• You can use only one union member at a time.
• All the union variables cannot be initialized or used with varying values at a
time.
• Union assigns one common storage space for all its members.

Difference between C Structure and C Union


The following table lists the key difference between the structure and union in C:

Structure Union

The size of the structure is equal to or greater The size of the union is the
than the total size of all of its members. size of its largest member.

The structure can contain data in multiple Only one member can contain
members at the same time. data at the same time.

It is declared using the union


It is declared using the struct keyword.
keyword.

You might also like