C Programming Unit 4
C Programming Unit 4
4.1 Introduction
Using C language we can create new data types. These data types are known as
User Defined data types & can be created by using Structures, Unions &
Enumerations.
Need for Structure
Arrays can store data of same data type. They can’t be used to store data of
different data types. For this Structures are used.
Structures
A structure is a collection of variables of different types under a single name. It
is used for storing different types of data.
3 aspects:
1. Defining a structure type
2. Declaring variables
3. Using & performing operations.
4.1.1 Structure Definition
The structure can be defined with the keyword struct followed by the name of
structure and opening brace with data elements of different type then closing brace
with semicolon.
General Form
struct [structure tag name]
{
type
membername1;
type
membername2;
……
}[variable
name]; E.g. struct book
{
char title[25];
int pages;
float price;
};
• Structure definition does not reserve any space in the memory.
• It is not possible to initialize the structure members during the structure
definition.
• A structure definition must always be terminated with a semicolon.
Example program:
#include<stdio.h>
struct name
{ char fname[20],lastname[20];
};
struct student
{ int sno,m1,m2,m3;
int tot; float avg;
struct name
sname;
}; void
main() {
struct student s[10]; float,avg; int n,i;
printf(“Enter the number of students \
n”); scanf(“%d”,&n); for(i=0;i<n;i++) {
printf(“Enter student details \n”);
scanf(“%d”,&s[i].sno); scanf((“%d%d
%d”,&s[i].m1, &s[i].m2, &s[i].m3); scanf(“%s”,
s[i].sname.fname);
scanf((“%s”,s[i].sname.lastname);
s[i].tot=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].tot/6.0;
}
printf(“Student Mark lists\n”); for(i=0;i<n;i++) printf(“%s\t%s\t
%f”,s[i].sname.fname, s[i].sname.lastname,s[i].avg);
}
Output:
Enter the number of students
2
E.g) s[i].sname.lastname
student
sn
m1
m2
m3
avg
name
fname
lastname
4.3 Pointer and Structures
It is possible to create a pointer to a structure. A Structure containing a member that is
a pointer to the same structure type is called self referential structure. A pointer variable
for the structure can be declared by placing an asterisk(*) in front of the structure
pointer variable.
Syntax:
struct namedstructuretype
*identifiername;
Example:
struct struct_name
{ data_type member_name1;
data_type
member_name2;
.....................................
}*ptr;
OR
struct struct_name *ptr;
Dot(.) operator is used to access the data using normal structure variable and arrow (-
>) is used to access the data using pointer variable.
E.g. Program:
#include<stdio.h>
#include<conio.h>
struct employee
{ char name[15]; int
empid,bsal;
float net,gross;
}; void main() { struct employee emp[10];
float hra,da,tax; int n,i,j; clrscr();
printf("Enter the number of employees\
n"); scanf("%d",&n); for(i=1;i<=n;i++)
{ printf("\nEnter the employee
name"); scanf("%s",emp[i].name);
printf("\ nEnter the employee id");
scanf("%d",&emp[i].empid);
printf("\nEnter the basic salary");
scanf("%d",&emp[i].bsal);
hra=((10*emp[i].bsal)/100);
da=((35*emp[i].bsal)/100);
tax=((15*emp[i].bsal)/100);
emp[i].gross=emp[i].bsal+hra+da;
emp[i].net=emp[i].gross-tax;
} printf("Employee Name Employee ID Employee Net Salary \
n"); for(i=1;i<=n;i++) printf("%s\t\t%d\t\t%f\
n",emp[i].name,emp[i].empid,emp[i].net); getch(); }
Output:
Enter the number of Employees
2
Enter the employee name
Anu
Enter the employee id
01
Enter the basic salary
1000
Enter the employee name
Meena
Enter the employee id
02
Enter the basic salary
2000
Employee Name Employee ID Net Salary
Anu 01 1300.000
Meena 02 2600.000
4.5 Example Program using structures and pointers
1. C program to read and print employee's record using structure
#include <stdio.h>
/*structure declaration*/
struct employee{ char
name[30]; int
empId;
float salary;
};
int main()
{
/*declare structure variable*/
struct employee emp;
Example
int N = 10; // Number of bytes to allocate
int *ptr; // Pointer variable to store address
ptr = (int *) malloc(N * sizeof(int)); // Allocate 10 * 4 bytes in memory
Here,
• ptr is a pointer to integer to store address of the allocated memory.
• (int *) is typecast required. As, I mentioned above that malloc() return void *.
Hence, to work with void pointer we must typecast it to suitable type.
• N * sizeof(int) - Since size of int is not fixed on all compilers. Hence, to get
size of integer on current compiler I have used sizeof() operator.
3. realloc() function
When working with huge data and if the allocated memory is not sufficient to store
data. In that case, we need to alter/update the size of an existing allocated memory
blocks (which has been created by either malloc() or calloc()).
We use realloc() function to alter/update the size of exiting allocated memory blocks.
The function may resize or move the allocated memory blocks to a new
location. Syntax void* realloc(ptr, updated_memory_size);
• Similar to all other functions for Dynamic Memory Allocation in C, it returns
void pointer. Which points to the address of existing or newly allocated
memory.
• ptr is a pointer to memory block of previously allocated memory.
• updated_memory_size is new (existing + new) size of the memory block.
C programming has a built-in library function free() to clear or release the unused
memory.
The free() function clears the pointer (assigns NULL to the pointer) to clear the
dynamically allocated memory. If pointer contains NULL, then free() does nothing
(because pointer will not be pointing at any memory addresses). If it contains any
address of dynamically allocated memory, free() will clear pointer by assigning
NULL. Syntax
free(ptr);
The function accepts a void pointer ptr. It points to previously allocated memory using
any of Dynamic Memory Allocation functions in C.
Example:
int N=10;
int *ptr;
// Allocate memory using malloc
ptr=(int *) malloc (N* size of (int));
//Free allocated memory
free(ptr);
• Linked list is a data structure which in turn can be used to implement other data
structures. Thus, it acts as building block to implement data structures like
stacks, queues and their variations.
• A linked list can be perceived as a train or a sequence of nodes in which each
node contain one or more data fields and a pointer to the next node.
START
1 2 3 4 5 6 7 X
In the above linked list, every node contains two parts- one integer and the other a
pointer to the next node. The left part of the node which contains data may include a
simple data type, an array or a structure. The right part of the node contains a pointer
to the next node (or address of the next node in sequence). The last node will have no
next node connected to it, so it will store a special value called NULL.
A singly linked list is the simplest type of linked list in which every node contains
some data and a pointer to the next node of the same data type. By saying that the
node contains a pointer to the next node we mean that the node stores the address of
the next node in sequence.
In this algorithm, we first initialize PTR with the address of start. So now PTR points
to the first node of the linked list.
Then in step 2 while loop is executed which is repeated till PTR processes the last
node, that is, until it encounters NULL.
In step 3, we apply the process to the current node.
In step 4, we move to the next node by making PTR point to the node whose address is
stored in the NEXT field.
The algorithm print the information stored in each node of the linked list is shown
below:
We will traverse each and every node of the list and while traversing every individual
node, we will increment the counter by 1. Once we reach NULL, that is when all the
nodes of the linked list have been traversed, the final value of the counter will be
displayed. Figure below shows the algorithm to print the number of nodes in a linked
list.
Consider the linked list shown in figure we have val=4, then the flow of the algorithm
can be explained as shown in figure
1 7 3 4 2 6 5 X
1 7 3 4 2 6 5 X
1 7 4 2 6 5 X
3
4.8.3 Insertion in a S ingly L inkedLis t
1 7 3 4 2 6 5 X
Insert a new node at the head of the list is straightforward. The main idea is that we
create a new node, set its next link to refer to the current head, and then set head to
point to the new node.
Algorithm addFirst(String newData):
create a new node v
containing newData
v.setNext(head) head = v size = size + 1
Example:
include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct test_struct
{
int val; struct
test_struct *next;
}; struct test_struct *head = NULL;
struct test_struct *curr = NULL;
struct test_struct* create_list(int
val)
{
printf("\n creating list with headnode as [%d]\n",val); struct test_struct *ptr
= (struct test_struct*)malloc(sizeof(struct test_struct)); if(NULL == ptr)
{ printf("\n Node creation failed \n"); return
NULL;
}
ptr->val = val; ptr-
>next = NULL; head =
curr = ptr; return ptr;
}
struct test_struct* add_to_list(int val, bool add_to_end)
{ if(NULL ==
head)
{
return (create_list(val));
} if(add_to_end) printf("\n Adding node to end of list with value [%d]\
n",val); else printf("\n Adding node to beginning of list with value [%d]\
n",val); struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct
test_struct)); if(NULL == ptr)
{ printf("\n Node creation failed \n"); return NULL;
}
ptr->val = val; ptr-
>next = NULL;
if(add_to_end)
{ curr->next = ptr; curr = ptr;
}
else { ptr->next = head; head = ptr;
}
return ptr;
}
struct test_struct* search_in_list(int val, struct test_struct **prev)
{
struct test_struct *ptr = head; struct test_struct
*tmp = NULL; bool found = false; printf("\n
Searching the list for value [%d] \n",val); while(ptr
!= NULL)
{
if(ptr->val == val)
{ found = true;
break; }
else
{
tmp = ptr; ptr = ptr->next;
} } if(true == found)
{ if(prev) *prev =
tmp; return ptr;
}
else
{ return NULL; } } int
delete_from_list(int val)
{ struct test_struct *prev = NULL; struct
test_struct *del = NULL; printf("\n Deleting
value [%d] from list\n",val); del =
search_in_list(val,&prev); if(del == NULL)
{ return -1; } else
{ if(prev != NULL)
prev->next = del-
>next; if(del == curr)
{ curr =
prev; }
else if(del == head)
{ head = del-
>next;
} } free(del); del =
NULL; return 0;
}
void print_list(void) { struct test_struct
*ptr = head; printf("\n -------Printing list
Start-------\n"); while(ptr != NULL)
{
printf("\n [%d] \n",ptr->val);
ptr = ptr->next;
}
printf("\n -------Printing list End-------\n"); return;
} int
main(void)
{
int i = 0, ret = 0; struct test_struct *ptr = NULL; print_list();
for(i = 5; i<10; i++) add_to_list(i,true); print_list(); for(i = 4;
i>0; i--) add_to_list(i,false); print_list(); for(i = 1; i<10; i += 4)
{ ptr = search_in_list(i, NULL); if(NULL == ptr) { printf("\n
Search [val = %d] failed, no such element found\n",i);
}
else
{
printf("\n Search passed [val = %d]\n",ptr->val); } print_list(); ret =
delete_from_list(i); if(ret != 0) { printf("\n delete [val = %d] failed, no such
element found\n",i);
}
else
{
printf("\n delete [val = %d] passed \n",i); } print_list(); } return
0; }
4.9 Typedef
The typedef keyword enables the programmer to create a new data type name by using an existing
data type.
By using typedef, no new data is created, rather an alternate name is given to a known data type.
Syntax: typedef existing_data_type new_data_type;
UNION
Union is derived data type contains collection of different data type or dissimilar elements. All
definition declaration of union variable and accessing member is similar to structure, but
instead of keyword struct the keyword union is used, the main difference between union and
structure is
lOMoARcPSD|12585645
Each member of structure occupy the memory location, but in the unions members share
memory. Union is used for saving memory and concept is useful when it is not necessary to
use all members of union at a time.
Where union offers a memory treated as variable of one type on one occasion where (struct),
it read number of different variables stored at different place of memory.
student
member2;
};
Like structure variable, union variable can be declared with definition or separately such as
Datatype member1;
}var1;
Union members can also be accessed by the dot operator with union variable and if we have
pointer to union then member can be accessed by using (arrow) operator as with structure.
Example:-
struct student
int i;
char ch[10];
};struct student s;
Here datatype/member structure occupy 12 byte of location is memory, where as in the union
side it occupy only 10 byte.
Nested of Union
union. Example:union a
int i; int
age; }; union
b{ char
name[10];
union a aa;
}; union b bb;
main()
struct a
int i;
lOMoARcPSD|12585645
char
ch[20]; };
struct b
int i;
char d[10];
}; union z
b b1;
z1.a1.i=10;
z1.a1.ch[10]= “ i“;
z1.b1.d[0]=”j “;
printf(“ “);
Storage Classes
Storage class in c language is a specifier which tells the compiler where and how to store
variables, its initial value and scope of the variables in a program. Or attributes of variable
is known as storage class or in compiler point of view a variable identify some physical
location within a computer where its string of bits value can be stored is known as storage
class.
The kind of location in the computer, where value can be stored is either in the memory
or in the register. There are various storage class which determined, in which of the two
location value would be stored. Syntax of declaring storage classes is:-
1 ) Automatic (auto)
lOMoARcPSD|12585645
2 ) Register (register)
3) Static (static) 4
) External (extern)
Examples:-
Storage-memory location
variable. Example:main( )
auto int i;
printf(“i=”,i);
The keyword used to declare this storage class is register. The features
are:-
Storage:-CPU register.
Life time :-till controls remains within function or blocks in which it is defined.
Register variable don’t have memory address so we can’t apply address operator on it. CPU
register generally of 16 bits or 2 bytes. So we can apply storage classes only for integers,
characters, pointer type.
Variable stored in register storage class always access faster than,which is always stored in
the memory. But to store all variable in the CPU register is not possible because of
limitation of the register pair.
And when variable is used at many places like loop counter, then it is better to declare it as
register class. Example:- main( )
{
lOMoARcPSD|12585645
+) printf(“%d”,i);
are:-
Storage:-memory location
Life time:- value of the variable persist or remain between different function
call. Example:main( )
reduce( );
reduce( );
reduce ( );
reduce(
){
+;
Output:-10,11,12
Features are:-
Declaration does not create variables, only it refer that already been created at somewhere
else. So, memory is not allocated at a time of declaration and the external variables are
declared at outside of all the function.
CS3251 Programming in C – UNIT IV
lOMoARcPSD|12585645
Example:-
int i,j;
void main( )
{ printf( “i=%d”,i );
receive ( );
reduce( );
}
receive( ) { i=i+2; printf(“on
increase i=%d”,i);
}
reduce( )
{
i=i-1; printf(“on reduce i=
%d”,i); }
Output:-i=0,2,4,3,2.
31