Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
24 views

C Programming Unit 4

Unit - 4 Notes

Uploaded by

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

C Programming Unit 4

Unit - 4 Notes

Uploaded by

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

CS3251 UNIT IV Notes

Computer Science (Anna University)

Scan to open on Studocu


UNIT IV STRUCTURES
Structure – Nested structures – Pointer and Structures –
Array of structures – Self referential structures – Dynamic memory
allocation – Singly linked list – typedef – Union – Storage classes and
Visibility.

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.

Rules for Structure members


1.A structure can have data of different types
2.A structure can’t contain an instance of itself.E.g. struct box {
struct box a; // not possible
};
3.A structure can contain members of other complete types.E.g.
struct name { char firstname[20]; char lastname[20];
}; struct person { struct
name personname; float
salary; }
4.A structure can contain a pointer to itself;
4.1.2 Declaration
Variables of structure type can be declared either at the time of structure
definition or after the structure definition.
General Form
struct structurename variablename[=initialization list];
E.g.
struct book b1,b2;
struct book b3={“CP”,500,385.00};
Accessing Members of Structure
There are two types of operators used for accessing members of a structure.
1. Direct member access operator (dot operator) (.)
2. Indirect member access operator (arrow operator) (->) Using
Dot operator General form:
structure variable name.member variable name E.g.
Suppose, we want to access title of structure variable b1, then, it can be
accessed as:
b1.title
We can also directly assign values to members.
b1.title= “CP”;
4.2 Structures within a Structure (Nested Structures)
A structure can be nested within another structure. Structure within structure is
known as nested structure i.e.) one structure can be declared inside other.

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

Enter student details


1 70 58 68 AjithKesav
2 90 86 95 RishikKesav
Student Mark lists
AjithKesav 70.000 RishikKesav
90.000

Accessing members in nested structure

outerstructure variable.innerstructure variable.member name

E.g) s[i].sname.lastname
student

sn

m1

m2

m3

tot nested structure

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.

1. Illustration of Structures using pointers


#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record1 = {1, "Raju",
90.5}; struct student *ptr; ptr = &record1;
printf("Records of Student: \n");
printf(" Id is: %d \n", ptr->id); printf(" Name is:
%s \n", ptr->name); printf(" Percentage is: %f \n\
n", ptr->percentage);
return 0;
}
Output:
Records of Student:
Id is: 1
Name is: Sankar
Percentage is: 90.500000
4.4 Array of Structures
Array of Structures is nothing but a collection of structures. It is an array whose
elements are of structure type. This is also called as Structure Array in C.
Consider the structure type struct student. This structure contains student
information like student name, s.no etc.
struct student
{ char name[20]; int sno,
m1, m2, m3; float
average;
};
Using a single structure variable we can store single student details. To store
information about several students, we have to create a separate variable for each
student. It is not feasible. So array of structures are used.
General form

struct structurename arrayname[size];

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;

/*read employee details*/ printf("\


nEnter details :\n");
printf("Name ?:"); gets(emp.name);
printf("ID ?:"); scanf("%d",&emp.empId);
printf("Salary ?:"); scanf("%f",&emp.salary);

/*print employee details*/ printf("\


nEntered detail is:"); printf("Name:
%s" ,emp.name);
printf("Id: %d" ,emp.empId);
printf("Salary: %f\n",emp.salary);
return 0;
}
Output:
Enter details :
Name ?:Raju
ID ?:007
Salary ?:76543

Entered detail is:


Name: Raju
Id: 007
Salary: 76543.000000

4.6 Self referential structures


Self referential Structures are those structures that contain a reference to data of its
same type. i.e in addition to other data a self referential structure contains a pointer to
a data that it of the same type as that of the structure. For example: consider the
structure node given as follows:
struct node
{
int val; struct
node *next;
};
Here the structure node will contain two types of data an integer val and next which
is a pointer a node. Self referential structure is the foundation of other data structures.
4.7 Dynamic memory allocation

Dynamic memory allocation refers to the process of manual memory management


(allocation and deallocation).
The functions supports for dynamic memory allocation are,
1. malloc() 2.
calloc()
3. realloc()
4. free()

1. malloc() function malloc() allocates N bytes in memory and return pointer to


allocated memory. The returned pointer contains link/handle to the allocated memory.
void * malloc(number_of_bytes);
• It returns void pointer (generic pointer). Which means we can easily typecast it
to any other pointer types.
• It accepts an integer number_of_bytes, i.e. total bytes to allocate in memory.
Note: malloc() returns NULL pointer on failure.

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.

2. calloc() function calloc() function allocates memory contiguously. It allocates

multiple memory blocks and initializes all blocks with 0 (NULL).

Note: malloc() allocates uninitialized memory blocks.


Syntax
void* calloc(number_of_blocks, number_of_bytes);
Here,
• Similar to malloc() it returns void pointer.
• It accepts two parameters number_of_blocks i.e. total blocks to allocate and
number_of_bytes i.e. bytes to allocate per block. Therefore, you can say that
calloc() will allocate total (number_of_blocks * number_of_bytes) bytes. Each
block initialized with 0 (NULL). Example:
int *ptr;
ptr = (int *) calloc(N, sizeof(int));
Here, all memory blocks are initialized with 0.

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.

Example // Original memory blocks


allocation

int N = 10; int *ptr;


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

// Increase the value of N


N = 50;
// Reallocate memory blocks
ptr = (int *) realloc(ptr, N * sizeof(int));
4. free() function

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);

4.8 Singly Linked List


• A linked list in simple terms is a linear collection of data elements. These data
elements are called nodes.

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

4.8.1 Traversing a singly linked list


Traversing a linked list means accessing the nodes of the list in order to perform some
operations on them. A Linked list always contains a pointer variable START which
stores the address of the first node of the list. The end of the list is marked by string
NULL or -1 in the NEXT field of the last node. For traversing the singly linked list,
we make use of another pointer variable PTR which points to the node that is correctly
being accessed. The algorithm to traverse a linked list is shown below:

Algorithm for traversing a linked list Step 1:


[INITIALIZE] SET PTR = START
Step 2: Repeat Steps 3 and 4 while PTR != NULL
Step 3:Apply Process to PTR->DATA Step 4:SET PTR
= PTR->NEXT
[END OF LOOP] 15
Step 5: EXIT
lOMoARcPSD|12585645

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:

Algorithm to print the information stored in each


node of the linked list
Step 1: [INITIALIZE] SET PTR = START
Step 2: Repeat Steps 3 and 4 while PTR != NULL
Step 3:Write PTR->DATA
Step 4:SET PTR = PTR->NEXT [END OF LOOP]
Step 5: EXIT

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.

Algorithm to print the number of nodes in the linked list Step 1:


[INITIALIZE] SET Count = 0
Step 2: [INITIALIZE] SET PTR = START
Step 3: Repeat Steps 4 and 5 while PTR != NULL Step 4:SET Count =
Count + 1
Step 5:SET PTR = PTR->NEXT
[END OF LOOP]

4.8.2 Searching for a value in a Linked list


Searching a linked list means to find a particular element in the linked list. A linked
list consists of two parts – the DATA part and NEXT part, where DATA stores the
relevant information and NEXT stores the address of the next node in the sequence.
Figure below shows the algorithm to search a linked list.
Algorithm to search an unsorted linked list Step 1:
[INITIALIZE] SET PTR = START
Step 2: Repeat Steps 3 while PTR != NULL Step 3:IF VAL = PTR-
>DATA
SET POS = PTR
Go To Step 5
ELSE
SET PTR = PTR->NEXT [END OF IF]
[END OF LOOP] Step 4: SET POS = NULL Step 5: EXIT

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

4.8.3 Insertion at the tail


If we keep a reference to the tail node, then it would be easy to insert an element at the
tail of the list. Assume we keep a tail node in the class of SLinkedList, the idea is to
create a new node, assign its next reference to point to a null object, set the next
reference of the tail to point to this new object, and then assign the tail reference itself
to this new node. Initially both head and tail point to null object.
Algorithm addLast(String newData):
create a new node v containing newData
v.setNext(null) if (head == null) { // list
is empty
head = v
} else { // list is not empty
tail.setNext(v)
} tail = v size
= size + 1

4.8.4 Deletion in a Singly Linked List


Deletion at the head
Removal of an element at the head of a singly linked list is relatively easy. However
removing a tail node is not easy.
Algorithm removeFirst()
if (head = = null) then
Indicate an error: the list is
empty tmp = head head =
head.getNext() tmp.setNext(null)
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;

It is used to create a new data using the existing type.


Syntax: typedef data type name;
Example: typedef int hours: hours hrs;/
* Now, hours can be used as new datatype */

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.

Syntax of union: union

student

datatype member1; datatype

member2;

};

Like structure variable, union variable can be declared with definition or separately such as

union union name

Datatype member1;

}var1;

Example:- union student s;

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

When one union is inside the another union it is called nested of

union. Example:union a

int i; int

age; }; union

b{ char

name[10];

union a aa;

}; union b bb;

There can also be union inside structure or structure in union.


Example:- void

main()

struct a

int i;
lOMoARcPSD|12585645

char

ch[20]; };

struct b

int i;

char d[10];

}; union z

struct a a1; struct

b b1;

}; union z z1; z1.b1.j=20;

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

storageclass datatype variable name;


There are four types of storage classes and all are keywords:-

1 ) Automatic (auto)
lOMoARcPSD|12585645

2 ) Register (register)

3) Static (static) 4
) External (extern)

Examples:-

auto float x; or float x;

extern int x; register

char c; static int y;

Compiler assume different storage class based on:-

1 ) Storage class:- tells us about storage place(where variable would be stored).

2) Intial value :-what would be the initial value of the variable.


If initial value not assigned, then what value taken by uninitialized variable.

3) Scope of the variable:-what would be the value of the variable of the


program.

4) Life time :- It is the time between the creation and distribution of a


variable or how long would variable exists.

1. Automatic storage class


The keyword used to declare automatic storage class is auto. Its features:-

Storage-memory location

Default initial value:-unpredictable value or garbage value.


Scope:-local to the block or function in which variable is defined.
Life time:-Till the control remains within function or block in which it is defined. It terminates
when function is released.

The variable without any storage class specifier is called automatic

variable. Example:main( )

auto int i;

printf(“i=”,i);

Register storage class

The keyword used to declare this storage class is register. The features

are:-

Storage:-CPU register.

Default initial value :-garbage value


Scope :-local to the function or block in which it is defined.

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

register int i; for(i=1;i<=12;i+

+) printf(“%d”,i);

3 Static storage class


The keyword used to declare static storage class is static. Its feature

are:-

Storage:-memory location

Default initial value:- zero


Scope :- local to the block or function in which it is defined.

Life time:- value of the variable persist or remain between different function

call. Example:main( )

reduce( );

reduce( );

reduce ( );

reduce(

){

static int x=10; printf(“%d”,x); x+

+;

Output:-10,11,12

External storage classes


The keyword used for this class is extern.

Features are:-

Storage:- memory area

Default initial value:-zero Scope :- global


Life time:-as long as program execution remains it retains.

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

You might also like