Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

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.
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;
In the case where we have a pointer to the structure, we can
also use the arrow operator to access the members.
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.
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. This feature has been added in the
C99 standard.
struct structure_name str = { .member1 =
value1, .member2 = value2, .member3 =
value3 };
The Designated Initialization is only supported in C but not in
C++.
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,
"GeeksforGeeks" },
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 =
GeeksforGeeks
Struct 2:
i = 1, c = A, f = 1.000000, s =
GeeksforGeeks
Struct 3
i = 5, c = a, f = 5.000000

typedef for Structures


The typedef keyword is used to define an alias for the already
existing datatype. In structures, we have to use the struct
keyword along with the structure name to define the variables.
Sometimes, this increases the length and complexity of the
code. We can use the typedef to define some new shorter
name for the structure.
Example
// C Program to illustrate the use of
typedef with
// structures
#include <stdio.h>

// defining structure
struct str1 {
int a;
};

// defining new name for str1


typedef struct str1 str1;

// another way of using typedef with


structures
typedef struct str2 {
int x;
} str2;

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;
...
}
...
}

2. Separate Structure Nesting


In this method, two structures are declared separately and then
the member structure is nested inside the parent structure.
Example
struct member_str {
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;
};

Accessing Nested Members


We can access nested Members by using the same ( . ) dot
operator two times as shown:
str_parent.str_child.member;

Example of Structure Nesting


// C Program to illustrate structure
nesting along with
// forward declaration
#include <stdio.h>

// child structure declaration


struct child {
int x;
char c;
};

// parent structure declaration


struct parent {
int a;
struct child b;
};

// driver code
int main()
{
struct parent var1 = { 25, 195, 'A' };

// accessing and printing nested


members
printf("var1.a = %d\n", var1.a);
printf("var1.b.x = %d\n", var1.b.x);
printf("var1.b.c = %c", var1.b.c);

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;

// Accessing structure members using


structure pointer
printf("%d %d", ptr->x, ptr->y);
return 0;
}
Output
1 2

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;

// accessing var2 members using var1


printf("var2.mem1: %d\nvar2.mem2:
%d", ptr1->next->mem1,
ptr1->next->mem2);

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>

// structure with padding


struct str1 {
char c;
int i;
};

struct str2 {
char c;
int i;
} __attribute((packed)) __; // using
structure packing

// driver code
int main()
{

printf("Size of str1: %d\n",


sizeof(struct str1));
printf("Size of str2: %d\n",
sizeof(struct str2));
return 0;
}
Output
Size of str1: 8
Size of str2: 5
As we can see, the size of the structure is varied when
structure packing is performed.
To know more about structure padding and packing, refer to
this article – Structure Member Alignment, Padding and Data
Packing.
Bit Fields
Bit Fields are used to specify the length of the structure
members in bits. When we know the maximum length of the
member, we can use bit fields to specify the size and reduce
memory consumption.
Syntax of Bit Fields
struct structure_name {
data_type member_name: width_of_bit-
field;
};

Example of Bit Fields


// C Program to illustrate bit fields in
structures
#include <stdio.h>

// declaring structure for reference


struct str1 {
int a;
char c;
};
// structure with bit fields
struct str2 {
int a : 24; // size of 'a' is 3 bytes
= 24 bits
char c;
};

// 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

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.

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

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.

Memory Allocation in C Union


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

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 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.

Dynamic Memory Allocation in C using malloc(), calloc(),


free() and realloc()
Last Updated : 08 Jul, 2024

Since C is a structured language, it has some fixed rules for


programming. One of them includes changing the size of an
array. An array is a collection of items stored at contiguous
memory locations.

As can be seen, the length (size) of the array above is 9. But


what if there is a requirement to change this length (size)? For
example,
 If there is a situation where only 5 elements are needed
to be entered in this array. In this case, the remaining 4
indices are just wasting memory in this array. So there is
a requirement to lessen the length (size) of the array from
9 to 5.
 Take another situation. In this, there is an array of 9
elements with all 9 indices filled. But there is a need to
enter 3 more elements in this array. In this case, 3 indices
more are required. So the length (size) of the array needs
to be changed from 9 to 12.
This procedure is referred to as Dynamic Memory
Allocation in C.
Therefore, C Dynamic Memory Allocation can be defined as
a procedure in which the size of a data structure (like Array) is
changed during the runtime.
C provides some functions to achieve these tasks. There are 4
library functions provided by C defined under <stdlib.h>
header file to facilitate dynamic memory allocation in C
programming. They are:
1. malloc()
2. calloc()
3. free()
4. realloc()

Let’s look at each of them in greater detail.


C malloc() method
The “malloc” or “memory allocation” method in C is used
to dynamically allocate a single large block of memory with
the specified size. It returns a pointer of type void which can
be cast into a pointer of any form. It doesn’t Initialize memory
at execution time so that it has initialized each block with the
default garbage value initially.
Syntax of malloc() in C
ptr = (cast-type*) malloc(byte-size)
For Example:

ptr = (int*) malloc(100 * sizeof(int));


Since the size of int is 4 bytes, this statement will allocate 400
bytes of memory. And, the pointer ptr holds the address of the
first byte in the allocated memory.

If space is insufficient, allocation fails and returns a NULL


pointer.
Example of malloc() in C
#include <stdio.h>
#include <stdlib.h>

int main()
{

// This pointer will hold the


// base address of the block created
int* ptr;
int n, i;

// Get the number of elements for the


array
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements:
%d\n", n);

// Dynamically allocate memory using


malloc()
ptr = (int*)malloc(n * sizeof(int));

// Check if the memory has been


successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not
allocated.\n");
exit(0);
}
else {

// Memory has been successfully


allocated
printf("Memory successfully
allocated using malloc.\n");

// Get the elements of the array


for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the
array
printf("The elements of the array
are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}

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.

If space is insufficient, allocation fails and returns a NULL


pointer.
Example of calloc() in C
#include <stdio.h>
#include <stdlib.h>

int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;

// Get the number of elements for the


array
n = 5;
printf("Enter number of elements:
%d\n", n);

// Dynamically allocate memory using


calloc()
ptr = (int*)calloc(n, sizeof(int));

// Check if the memory has been


successfully
// allocated by calloc or not
if (ptr == NULL) {
printf("Memory not
allocated.\n");
exit(0);
}
else {

// Memory has been successfully


allocated
printf("Memory successfully
allocated using calloc.\n");

// Get the elements of the array


for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the
array
printf("The elements of the array
are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[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()
{

// This pointer will hold the


// base address of the block created
int *ptr, *ptr1;
int n, i;

// Get the number of elements for the


array
n = 5;
printf("Enter number of elements:
%d\n", n);

// Dynamically allocate memory using


malloc()
ptr = (int*)malloc(n * sizeof(int));

// Dynamically allocate memory using


calloc()
ptr1 = (int*)calloc(n, sizeof(int));

// Check if the memory has been


successfully
// allocated by malloc or not
if (ptr == NULL || ptr1 == NULL) {
printf("Memory not
allocated.\n");
exit(0);
}
else {

// Memory has been successfully


allocated
printf("Memory successfully
allocated using malloc.\n");

// Free the memory


free(ptr);
printf("Malloc Memory
successfully freed.\n");

// Memory has been successfully


allocated
printf("\nMemory successfully
allocated using calloc.\n");

// Free the memory


free(ptr1);
printf("Calloc Memory
successfully freed.\n");
}

return 0;
}

Output
Enter number of elements: 5
Memory successfully allocated using
malloc.
Malloc Memory successfully freed.

Memory successfully allocated using


calloc.
Calloc 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'.

If space is insufficient, allocation fails and returns a NULL


pointer.
Example of realloc() in C
#include <stdio.h>
#include <stdlib.h>

int main()
{

// This pointer will hold the


// base address of the block created
int* ptr;
int n, i;

// Get the number of elements for the


array
n = 5;
printf("Enter number of elements:
%d\n", n);

// Dynamically allocate memory using


calloc()
ptr = (int*)calloc(n, sizeof(int));

// Check if the memory has been


successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not
allocated.\n");
exit(0);
}
else {

// Memory has been successfully


allocated
printf("Memory successfully
allocated using calloc.\n");

// Get the elements of the array


for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the
array
printf("The elements of the array
are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}

// Get the new size for the array


n = 10;
printf("\n\nEnter the new size of
the array: %d\n", n);

// Dynamically re-allocate memory


using realloc()
ptr = (int*)realloc(ptr, n *
sizeof(int));

if (ptr == NULL) {
printf("Reallocation
Failed\n");
exit(0);
}

// Memory has been successfully


allocated
printf("Memory successfully re-
allocated using realloc.\n");

// Get the new elements of the


array
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the
array
printf("The elements of the array
are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}

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,

Enter the new size of the array: 10


Memory successfully re-allocated using
realloc.
The elements of the array are: 1, 2, 3,
4, 5, 6, 7, 8, 9, 10,

One another example for realloc() method is:


#include <stdio.h>
#include <stdlib.h>
int main()
{
int index = 0, i = 0, n,
*marks; // this marks pointer
hold the base address
// of the block created
int ans;
marks = (int*)malloc(sizeof(
int)); // dynamically allocate
memory using malloc
// check if the memory is
successfully allocated by
// malloc or not?
if (marks == NULL) {
printf("memory cannot be
allocated");
}
else {
// memory has successfully
allocated
printf("Memory has been
successfully allocated by "
"using malloc\n");
printf("\n marks = %pc\n",
marks); // print the base
or beginning
// address of
allocated memory
do {
printf("\n Enter Marks\n");
scanf("%d", &marks[index]);
// Get the marks
printf("would you like to add
more(1/0): ");
scanf("%d", &ans);
if (ans == 1) {
index++;
marks = (int*)realloc(
marks,
(index + 1)
* sizeof(
int)); //
Dynamically reallocate
//
memory by using realloc
// check if the memory is
successfully
// allocated by realloc
or not?
if (marks == NULL) {
printf("memory cannot
be allocated");
}
else {
printf("Memory has
been successfully "
"reallocated
using realloc:\n");
printf(
"\n base address
of marks are:%pc",
marks); ////print
the base or

///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

Singly linked list in C


Data structures are crucial elements in computer
programming because they make data handling and storage
efficient. The linked list is a typical data structure. In this blog
post, we will examine the concept of a single linked list in the
C programming language. We'll go over its operations,
definition, and example code syntax and outputs.
Each node in a singly linked list has a data element and a
reference to the node after it in the list, making it a linear data
structure. The list's head node is the first node, while the last
node points to NULL to denote the list's end.
A structure for each list node must be constructed to define a
single linked list in C. The structure should have two fields: a
data field for storing the actual data and a pointer field for
holding a reference to the subsequent node.
1. struct Node {
2. int data;
3. struct Node* next;
4. };
We must first initialize the head reference to NULL, which
denotes an empty list, in order to establish a single linked list.
After that, we may add nodes to the list by dynamically
allocating memory for each node and connecting them with
the next pointer.
1. struct Node* head = NULL; // Initializing an empty list
2.
3. void insert(int value) {
4. struct Node* newNode = (struct Node*)malloc(sizeof(
struct Node));
5. newNode->data = value;
6. newNode->next = NULL;
7.
8. if (head == NULL) {
9. head = newNode;
10. } else {
11. struct Node* current = head;
12. while (current->next != NULL) {
13. current = current->next;
14. }
15. current->next = newNode;
16. }
17. }
We must first initialize the head reference to NULL, which
denotes an empty list, in order to establish a single linked list.
After that, we may add nodes to the list by dynamically
allocating memory for each node and connecting them with
the next pointer.
1. void traverse() {
2. struct Node* current = head;
3. while (current != NULL) {
4. printf("%d ", current->data);
5. current = current->next;
6. }
7. }
A singly linked list can be searched for an element by
traversing the list and comparing each node's data with the
desired value. If a match is made, the relevant node is
returned; if not, NULL is returned to show that the element is
not present in the list.
1. struct Node* search(int value) {
2. struct Node* current = head;
3. while (current != NULL) {
4. if (current->data == value) {
5. return current;
6. }
7. current = current->next;
8. }
9. return NULL;
10. }
To remove a component from a singly linked list, locate the
node that contains the desired value and modify the links to
the preceding and following nodes accordingly. Additionally,
the memory that the destroyed node used must be freed.
1. void delete(int value) {
2. if (head == NULL) {
3. printf("List is empty.");
4. return;
5. }
6.
7. struct Node* current = head;
8. struct Node* previous = NULL;
9.
10. while (current != NULL) {
11. if (current->data == value) {
12. if (previous == NULL) {
13. head = current->next;
14. } else {
15. previous->next = current->next;
16. }
17. free(current);
18. return;
19. }
20. previous = current;
21. current = current->next;
22. }
23.
24. printf("Element not found in the list.");
25. }
Example:
Let's create a list, add entries, and perform various operations
on it to show how a single linked list is used.
1. #include <stdio.h>
2. #include <stdlib.h>
3.
4. // Singly Linked List structure
5. struct Node {
6. int data;
7. struct Node* next;
8. };
9.
10. // Global head pointer
11. struct Node* head = NULL;
12.
13. // Function to insert a node at the end of the list
14. void insert(int value) {
15. // Create a new node
16. struct Node* newNode = (struct Node*)malloc(si
zeof(struct Node));
17. newNode->data = value;
18. newNode->next = NULL;
19.
20. // Check if the list is empty
21. if (head == NULL) {
22. head = newNode;
23. } else {
24. // Traverse to the end of the list
25. struct Node* current = head;
26. while (current->next != NULL) {
27. current = current->next;
28. }
29. // Link the new node to the last node
30. current->next = newNode;
31. }
32. }
33.
34. // Function to traverse and print the list
35. void traverse() {
36. struct Node* current = head;
37. while (current != NULL) {
38. printf("%d ", current->data);
39. current = current->next;
40. }
41. }
42.
43. int main() {
44. // Insert elements into the list
45. insert(10);
46. insert(20);
47. insert(30);
48. insert(40);
49.
50. // Traverse and print the list
51. printf("List: ");
52. traverse();
53.
54. return 0;
55. }
List: 10 20 30 40
C typedef

The typedef is a keyword that is used to provide existing data


types with a new name. The C typedef keyword is used to
redefine the name of already existing data types.
When names of datatypes become difficult to use in programs,
typedef is used with user-defined datatypes, which behave
similarly to defining an alias for commands.
C typedef Syntax
typedef existing_name alias_name;

After this declaration, we can use the alias_name as if it were


the real existing_name in out C program.
Example of typedef in C
typedef long long ll;

Below is the C program to illustrate how to use typedef.


// C program to implement typedef
#include <stdio.h>

// defining an alias using typedef


typedef long long ll;

// Driver code
int main()
{
// using typedef name to declare
variable
ll var = 20;
printf("%ld", var);

return 0;
}
Output
20

You might also like