C Structures and Unions Explained
C Structures and Unions Explained
Structure:
struct tag_name
{
data_type member1;
data_type member2;
-------------
-------------
};
ISE, DSCE 1
DEFINING A STRUCTURE
• Structures must be defined first for their format that may be used later to
declare structure variables. Let us use an example to illustrate the process
of structure definition and the creation of structure variables.
• Consider a Student database consisting of name, rollno, marks. We can define
a structure to hold this information as follows:
struct student
{
char name[20]:
int rollno;
float percentage;
};
• The keyword struct declares a structure to hold the details of three data fields,
namely
• name, rollno, percentage. These fields are called structure elements or
members.
• Each member may belong to a different type of data. student is the name of
the structure and is called the structure tag.
• The tag name can be used to declare a structure variable.
• The above definition describes a format called template to represent
information as shown below:
ISE, DSCE 2
For example, the statement
struct student sl, s2, s3; declares s1, s2 and s3 as variables of type struct student
We can also use scanf to give the values through the keyboard.
scanf("%s", [Link]);
scanf("%d", &[Link]); are valid input statements.
ISE, DSCE 3
Note: The definition and the declaration of structures can be placed either in local
or scope when the program has only main() function. But in case the program has
more than one function then it is placed in global scope to be accessed by both
functions. If it is made local to a function then it can be accessed by only that
function.
Initialization of Structure
C language does not permit the initialization of individual structure members within
the template.
The initialization must be done only in the declaration of the actual variables.
Note that the compile-time initialization of a structure variable must have the
following elements:
ISE, DSCE 4
Example program :
• The typedef keyword gives a meaningful name to the existing data type which
helps other users to understand the program more easily.
• It can be used with structures to increase code readability and we don't have
to type struct repeatedly.
typedef in structures
ISE, DSCE 5
Here s is the type name.
The type_name represents structure definition associated with it and therefore can
be used to declare structure variables as shown below:
Example Program: use typedef to input and output one student details consisting name,
rollno, percentage.
UNIONS
ISE, DSCE 6
• Many union variables can be created in a program and memory will be
allocated for each union variable separately.
• The table below will help you how to form a C union, declare a union,
initializing and accessing the members of the union.
#include <stdio.h>
#include <string.h>
Union student
{
char name[20];
char subject[20];
float percentage;
};
int main()
{
union student record1;
union student record2;
ISE, DSCE 7
printf(" Subject : %s \n", [Link]);
printf(" Percentage : %f \n\n", [Link]);
strcpy([Link], "Physics");
printf(" Subject : %s \n", [Link]);
[Link] = 99.50;
printf(" Percentage : %f \n", [Link]);
return 0;
}
Output:
Union record1 values example
Name :
Subject :
Percentage : 86.500000;
Union record2 values example
Name : Mani
Subject : Physics
Percentage : 99.500000
There are 2 union variables declared in this program to understand the difference
in accessing values of union members.
ISE, DSCE 8
Record2 union variable:
• If we want to access all member values using union, we have to access the
member before assigning values to other members as shown in record2
union variable in this program.
• Each union members are accessed in record2 example immediately after
assigning values to them.
• If we don‟t access them before assigning values to other member, member
name and value will be over written by other member as all members are
using same memory.
• We can‟t access all members in union at same time but structure can do
that.
In this program, union variable “record” is declared while declaring union itself as shown in
the below program.
#include <stdio.h>
#include <string.h>
union student
{
char name[20]; char subject[20]; float percentage;
}record;
int main()
{
strcpy([Link], "Raju");
strcpy([Link], "Maths");
[Link] = 86.50;
printf(" Name : %s \n", [Link]);
printf(" Subject : %s \n", [Link]);
printf(" Percentage : %f \n", [Link]);
return 0;
}
Output:
Name :
Subject :
Percentage : 86.500000
We can access only one member of union at a time. We can‟t access all member
values at the same time in union. But, structure can access all member values at
the same time. This is because, Union allocates one common storage space for all
ISE, DSCE 9
its members. Where as Structure allocates storage space for all its members
separately.
Self-Referential Structures
• A structure can have members which point to a structure variable of the same
type.
• These types of structures are called self-referential structures and are widely
used in dynamic data structures like trees, linked list, etc.
• The following is a definition of a self-referential structure.
struct node
{
int data;
struct node *next;
};
ISE, DSCE 10
Here, next is a pointer to a struct node variable.
Pointer to Structure
ISE, DSCE 11
• Where ptr refers to a structure- type pointer variable and the operator → is
comparable to the period (.) operator. The associativity of this operator is also
left-to-right.
• The operator → can be combined with the period operator (.) to access a
submember within a structure. Hence, a submember can be accessed by writing
ptr → [Link]
struct Student
{
int roll_no;
char name[30];
char branch[40];
int batch;
};
int main()
{
s1.roll_no = 27;
strcpy([Link], "Kamlesh Joshi");
strcpy([Link], "Computer Science And Engineering");
[Link] = 2019;
return 0;
}
Out Put
Roll Number: 27
Name: Kamlesh Joshi
Branch: Computer Science And Engineering
Batch: 2019
ISE, DSCE 12
// C Program to demonstrate Structure pointer
#include <stdio.h>
#include <string.h>
int main()
{
ptr = &s;
// Taking inputs
printf("Enter the Roll Number of Student\n");
scanf("%d", &ptr->roll_no);
printf("Enter Name of Student\n");
scanf("%s", &ptr->name);
printf("Enter Branch of Student\n");
scanf("%s", &ptr->branch);
printf("Enter batch of Student\n");
scanf("%d", &ptr->batch);
return 0;
}
ISE, DSCE 13
Pointer to Function
Call by value:
#include<stdio.h>
struct employee
{
char name[20];
char city[20];
int pin;
};
void display(struct employee e);
void main ( )
{
struct employee e;
printf("Enter employee information name,city,pin\n");
scanf("%s %s %d ",[Link],[Link],&[Link]);
display(e);
}
void display(struct employee e)
{
printf("Printing the details....\n");
printf("%s %s %d",[Link],[Link],[Link]);
}
OUT PUT
Enter employee information name,city,pin
Praveen bangalore 560016
Printing the details….
Praveen bangalore 560016
Call by Reference
In the function call, the address of the structure variable is used. The argument in
the function header and declaration is to be declared as a pointer to a structure
variable.
Note :
-> is the member selection operator. (minus sign followed by greater than symbol)
ISE, DSCE 14
Call by reference :
#include<stdio.h>
struct employee
{
char name[20];
char city[20];
int pin;
};
void display(struct employee *e);
void main ( )
{
struct employee e;
printf("Enter employee information name,city,pinn");
scanf("%s %s %d ",[Link],[Link],&[Link]);
display(&e);
}
void display(struct employee *e)
{
printf("Printing the details....\n");
printf("%s %s %d",e->name,e->city,e->pin);
}
A data structure is said to be linear if its elements form a sequence or a linear list.
The linear data structures like an array, stacks, queues and linked lists organize
data in linear order. A data structure is said to be non linear if its elements form a
hierarchical classification where, data items appear at various levels.
Trees and Graphs are widely used non-linear data structures. Tree and graph
structures represent hierarchical relationship between individual data elements.
Graphs are nothing but trees with certain restrictions removed.
ISE, DSCE 15
Data structures are divided into two types:
1. Primitive data structures.
2. Non-primitive data structures.
Primitive Data Structures are the basic data structures that directly operate upon
the machine instructions. They have different representations on different
computers. Integers, floating point numbers, character constants, string constants
and pointers come under this category.
Non-primitive data structures are more complicated data structures and are
derived from primitive data structures. They emphasize on grouping same or
different data items with relationship between each data item. Arrays, lists and files
come under this category. Figure shows the classification of data structures.
1. Traversing
2. Searching
3. Inserting
4. Deleting
5. Sorting
6. Merging
1. Traversing- It is used to access each data item exactly once so that it can be
processed.
2. Searching- It is used to find out the location of the data item if it exists in the
given collection of data items.
3. Inserting- It is used to add a new data item in the given collection of data items.
4. Deleting- It is used to delete an existing data item from the given collection of
data items.
5. Sorting- It is used to arrange the data items in some order i.e. in ascending or
descending order in case of numerical data and in dictionary order in case of
alphanumeric data.
ISE, DSCE 16
6. Merging- It is used to combine the data items of two sorted files into single file
in the sorted form.
ISE, DSCE 17
• returns null pointer if it couldn‟t able to allocate requested amount of
memory.
• The expression results in a NULL pointer if the memory cannot be allocated.
Example
ptr = (float*) malloc(100 * sizeof(float));
The above statement allocates 400 bytes of memory. It's because the size of float
is 4 bytes. And, the pointer ptr holds the address of the first byte in the allocated
memory.
2. CALLOC():
• calloc () function is also like malloc () function. But calloc () initializes the
allocated memory to zero. But, malloc() doesn‟t.
• The name "calloc" stands for contiguous allocation.
Example:
ptr = (float*) calloc(25, sizeof(float));
3. REALLOC():
• Realloc () function modifies the allocated memory size by malloc () and
calloc () functions to new size.
• If enough space doesn‟t exist in memory of current block to extend, new
block is allocated for the full size of reallocation, then copies the existing
data to new block and then frees the old block.
Example:
ptr = realloc(ptr, x);
Here, ptr is reallocated with a new size x.
4. FREE():
• free () function frees the allocated memory by malloc (), calloc (), realloc
() functions and returns the memory to the system.
• You must explicitly use free() to release the space.
ISE, DSCE 18
Example:
free(ptr);
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
// if memory cannot be allocated
if(ptr == NULL)
{
printf(“Error! Memory not allocated.”);
exit(0);
}
printf(“Enter elements: “);
for(I = 0; I < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
return 0;
}
Output
Enter number of elements: 3
Enter elements: 100
20
36
Sum = 156
ISE, DSCE 19
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
Output
Example 3: realloc()
#include <stdio.h>
#include <stdlib.h>
int main()
ISE, DSCE 20
{
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Addresses of previously allocated memory:\n");
for(i = 0; i < n1; ++i)
printf("%pc\n",ptr + i);
printf("\nEnter the new size: ");
scanf("%d", &n2);
// rellocating the memory
ptr = realloc(ptr, n2 * sizeof(int));
printf("Addresses of newly allocated memory:\n");
for(i = 0; i < n2; ++i)
printf("%pc\n", ptr + i);
free(ptr);
return 0;
}
Output
Enter size: 2
Addresses of previously allocated memory:
26855472
26855476
ISE, DSCE 21
Memory size can‟t be modified while Memory size can be modified while
execution. execution.
Example: array Example: Linked list
malloc() calloc()
It allocates only single block of requested It allocates multiple blocks of requested
memory memory
int *ptr; int *ptr;
ptr = malloc( 20 * sizeof(int) ); Ptr = calloc( 20, 20 * sizeof(int) );
For the above, 20*4 bytes of memory For the above, 20 blocks of memory will
only allocated in one block. Total = 80 be created and each contains 20*4
bytes bytes of memory. Total = 1600 bytes
malloc () doesn‟t initializes the allocated calloc () initializes the allocated memory
memory. It contains garbage values to zero
type cast must be done since this Same as malloc () function int *ptr;
function returns void pointer int *ptr; ptr = (int*)calloc( 20, 20 * sizeof(int) );
ptr = (int*)malloc(sizeof(int)*20 );
Recursive Algorithms
The process in which a function calls itself directly or indirectly is called recursion
and the corresponding function is called a recursive function. Using a recursive
algorithm, certain problems can be solved quite easily.
Need of Recursion
Recursion is an amazing technique with the help of which we can reduce the length
of our code and make it easier to read and write. It has certain advantages over
the iteration technique which will be discussed later. A task that can be defined with
its similar subtask, recursion is one of the best solutions for it. For example; The
Factorial of a number.
Properties of Recursion:
ISE, DSCE 22
Example:
#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( )
int factorial(int);
int n,f;
printf("Enter the number: ");
scanf("%d",&n);
f=factorial(n);
printf("Factorial of the number is %d",f);
getch();
}
int factorial(int n)
{
int f;
if(n==1)
return 1;
else
f=n*factorial(n-1);
return f;
}
Sparse Matrices.
A sparse matrix is a matrix in which most of the elements are zero. By contrast, if
most of the elements are nonzero, then the matrix is considered dense. When
storing and manipulating sparse matrices on a computer, it is beneficial and often
necessary to use specialized algorithms and data structures that take advantage
of the sparse structure of the matrix. Operations using standard dense- matrix
structures and algorithms are slow and inefficient when applied to large sparse
matrices as processing and memory are wasted on the zeroes. Sparse data is by
nature more easily compressed and thus require significantly less storage. Some
very large sparse matrices are infeasible to manipulate using standard dense-
matrix algorithms.
ISE, DSCE 23
Storing a sparse matrix
1. Triplet Representation
2. Linked Representation
1. Triplet Representation
In this representation, we consider only non-zero values along with their row and
column index values. Each non zero value is a triplet of the form (R,C,Value) where
R represents the row in which the value appears, C represents the column in which
the value appears and Value represents the non- zero value itself. In this
representation, the 0th row stores total rows, total columns and total non-zero
values in the matrix.
For example, consider a matrix of size 5 X 6 containing 6 number of non-zero values.
This matrix can be represented as shown in the image...
In above example matrix, there are only 6 non-zero elements ( those are 9, 8, 4, 2, 5
& 2) and matrix size is 5 X 6. We represent this matrix as shown in the above image.
Here the first row in the right side table is filled with values 5, 6 & 6 which indicates
that it is a sparse matrix with 5 rows, 6 columns & 6 non-zero values. The second
row is filled with 0, 4, & 9 which indicates the non-zero value 9 is at the 0th-row 4th
column in the Sparse matrix. In the same way, the remaining non-zero values also
ISE, DSCE 24
follow a similar pattern.
Example Program
#include<stdio.h>
int main()
{
int S[10][10],m,n,i,k=0,size=0;
printf("Enter number of rows in the matrix : ");
scanf("%d",&m);
printf("Enter number of columns in the matrix : ");
scanf("%d",&n);
printf("Enter elements in the matrix : ");
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
scanf("%d",&S[i][j]);
printf("The matrix is \n");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
printf(" %d ",S[i][j]);
if (S[i][j] != 0)
size++;
}
printf("\n");
}
int M[3][size];
ISE, DSCE 25
for (int j=0; j<size; j++)
printf(" %d ", M[i][j]);
printf("\n");
}
return 0;
}
ISE, DSCE 26