Professional Documents
Culture Documents
4 unit 54
4 unit 54
// Driver code
int main()
{
// variable declaration after
structure template
// initialization with initializer
list and designated
// initializer list
struct str1 var1 = { 1, 'A', 1.00,
"GeeksforGeeks" },
var2;
struct str2 var3 = { .ff = 5.00, .ii =
5, .cc = 'a' };
return 0;
}
Output
Struct 1:
i = 1, c = A, f = 1.000000, s =
GeeksforGeeks
Struct 2:
i = 1, c = A, f = 1.000000, s =
GeeksforGeeks
Struct 3
i = 5, c = a, f = 5.000000
// defining structure
struct str1 {
int a;
};
int main()
{
// creating structure variables using
new names
str1 var1 = { 20 };
str2 var2 = { 314 };
printf("var1.a = %d\n", var1.a);
printf("var2.x = %d", var2.x);
return 0;
}
Output
var1.a = 20
var2.x = 314
Nested Structures
C language allows us to insert one structure into another as a
member. This process is called nesting and such structures are
called nested structures. There are two ways in which we can
nest one structure into another:
1. Embedded Structure Nesting
In this method, the structure being nested is also declared
inside the parent structure.
Example
struct parent {
int member1;
struct member_str member2 {
int member_str1;
char member_str2;
...
}
...
}
struct parent {
int member1;
struct member_str member2;
...
}
One thing to note here is that the declaration of the structure
should always be present before its definition as a structure
member. For example, the declaration below is invalid as the
struct mem is not defined when it is declared inside the parent
structure.
struct parent {
struct mem a;
};
struct mem {
int var;
};
// driver code
int main()
{
struct parent var1 = { 25, 195, 'A' };
return 0;
}
Output
var1.a = 25
var1.b.x = 195
var1.b.c = A
Structure Pointer in C
We can define a pointer that points to the structure like any
other variable. Such pointers are generally called Structure
Pointers. We can access the members of the structure pointed
by the structure pointer using the ( -> ) arrow operator.
Example of Structure Pointer
// C program to illustrate the structure
pointer
#include <stdio.h>
// structure declaration
struct Point {
int x, y;
};
int main()
{
struct Point str = { 1, 2 };
// p2 is a pointer to structure p1
struct Point* ptr = &str;
Self-Referential Structures
The self-referential structures in C are those structures that
contain references to the same type as themselves i.e. they
contain a member of the type pointer pointing to the same
structure type.
Example of Self-Referential Structures
struct structure_name {
data_type member1;
data_type member2;
struct structure_name* str;
}
// C program to illustrate the self
referential structures
#include <stdio.h>
// structure template
typedef struct str {
int mem1;
int mem2;
struct str* next;
}str;
// driver code
int main()
{
str var1 = { 1, 2, NULL };
str var2 = { 10, 20, NULL };
// assigning the address of var2 to
var1.next
var1.next = &var2;
// pointer to var1
str *ptr1 = &var1;
return 0;
}
Output
var2.mem1: 10
var2.mem2: 20
Such kinds of structures are used in different data structures
such as to define the nodes of linked lists, trees, etc.
C Structure Padding and Packing
Technically, the size of the structure in C should be the sum
of the sizes of its members. But it may not be true for most
cases. The reason for this is Structure Padding.
Structure padding is the concept of adding multiple empty
bytes in the structure to naturally align the data members in
the memory. It is done to minimize the CPU read cycles to
retrieve different data members in the structure.
There are some situations where we need to pack the structure
tightly by removing the empty bytes. In such cases, we use
Structure Packing. C language provides two ways for
structure packing:
1. Using #pragma pack(1)
2. Using __attribute((packed))__
Example of Structure Padding and Packing
// C program to illustrate structure
padding and packing
#include <stdio.h>
struct str2 {
char c;
int i;
} __attribute((packed)) __; // using
structure packing
// driver code
int main()
{
// driver code
int main()
{
printf("Size of Str1: %d\nSize of
Str2: %d",
sizeof(struct str1),
sizeof(struct str2));
return 0;
}
Output
Size of Str1: 8
Size of Str2: 4
As we can see, the size of the structure is reduced when using
the bit field to define the max size of the member ‘a’.
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.
Limitations 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.
C Unions
Syntax of Union in C
The syntax of the union in C can be divided into three steps
which are as follows:
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
// driver code
int main()
{
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.
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);
Structure Union
The size of the structure is equal to The size of the union is
or greater than the total size of all the size of its largest
of its members. member.
The structure can contain data in Only one member can
multiple members at the same contain data at the
time. same time.
Structure Union
It is declared using the struct It is declared using the
keyword. union keyword.
int main()
{
return 0;
}
Output
Enter number of elements:7
Entered number of elements: 7
Memory successfully allocated using
malloc.
The elements of the array are: 1, 2, 3,
4, 5, 6, 7,
C calloc() method
1. “calloc” or “contiguous allocation” method in C is used
to dynamically allocate the specified number of blocks of
memory of the specified type. it is very much similar to
malloc() but has two different points and these are:
2. It initializes each block with a default value ‘0’.
3. It has two parameters or arguments as compare to
malloc().
Syntax of calloc() in C
ptr = (cast-type*)calloc(n, element-
size);
here, n is the no. of elements and
element-size is the size of each element.
For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25
elements each with the size of the float.
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
return 0;
}
Output
Enter number of elements: 5
Memory successfully allocated using
calloc.
The elements of the array are: 1, 2, 3,
4, 5,
C free() method
“free” method in C is used to dynamically de-allocate the
memory. The memory allocated using functions malloc() and
calloc() is not de-allocated on their own. Hence the free()
method is used, whenever the dynamic memory allocation
takes place. It helps to reduce wastage of memory by freeing
it.
Syntax of free() in C
free(ptr);
Example of free() in C
#include <stdio.h>
#include <stdlib.h>
int main()
{
return 0;
}
Output
Enter number of elements: 5
Memory successfully allocated using
malloc.
Malloc Memory successfully freed.
C realloc() method
“realloc” or “re-allocation” method in C is used to
dynamically change the memory allocation of a previously
allocated memory. In other words, if the memory previously
allocated with the help of malloc or calloc is insufficient,
realloc can be used to dynamically re-allocate memory. re-
allocation of memory maintains the already present value and
new blocks will be initialized with the default garbage value.
Syntax of realloc() in C
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size
'newSize'.
int main()
{
if (ptr == NULL) {
printf("Reallocation
Failed\n");
exit(0);
}
free(ptr);
}
return 0;
}
Output
Enter number of elements: 5
Memory successfully allocated using
calloc.
The elements of the array are: 1, 2, 3,
4, 5,
///beginning address of
///allocated memory
}
}
} while (ans == 1);
// print the marks of the
students
for (i = 0; i <= index; i++) {
printf("marks of students %d
are: %d\n ", i,
marks[i]);
}
free(marks);
}
return 0;
}
Output
// Driver code
int main()
{
// using typedef name to declare
variable
ll var = 20;
printf("%ld", var);
return 0;
}
Output
20