PSP Module 5
PSP Module 5
MODULE - V
DIGITAL NOTES
B.E
(I YEAR – II SEM)
(2021-22)
DEPARTMENT OF CSE
SHRI MADHWA VADIRAJA INSTITUTE OF
TECHNOLOGY AND MANAGEMENT
1
5.1. INTRODUCTION TO STRUCTURES
C Structure is a collection of different data types which are grouped together and each
element in a C structure is called member.
In real life we need to have different data types for ex: To maintain employee information.
We should have information such as name, age, qualification, salary etc. here to maintain
the information of employee dissimilar data types required. Name & qualification are char
data type, age is integer, and salary is float. You can create this information separately but,
better approach will be collection of this information under single name because all these
information are related to person.
Structure is a collection of heterogeneous type of data i.e. different types of data. The
various individual components, in a structure can be accessed and processed separately. A
structure is a collection of variables referenced under a name, providing a convenient
means of keeping related information. A structure declaration forms a template that may
be used to create structure objects.
• A normal C variable can hold only one data of one data type at a
time. • An array can hold group of data of same data type.
• A structure can hold group of data of different data types
• Data types can be int, char, float, double and long double etc.
Features of Structures:
To copy elements of one array to another array of same data type elements are copied one
by one. It is not possible to copy elements at a time. Where as in structure it is possible to
copy the contents of all structure elements of different data types to another structure var
of its type using assignment (=) operator. It is possible because structure elements are
stored in successive memory locations. Nesting of structures is also possible.
2
5.1.1. Defining a structure:
‘struct’ keyword is used to define a structure, struct define a new data type which is a
collection of different type of data.
Syntax :
struct structure_name
{
//Statements
};
Example :
struct Book
{
char name[15];
float price;
int pages;
};
Here the struct Book declares a structure to hold the details of book which consists of
three data fields, namely name, price and pages. These fields are called structure elements
or members. Each member can have different data type, like in this case, name is of char
type and price is of float type etc. Book is the name of the structure and is called structure
tag.
Like any other data type, structure variable can also be initialized at compile time.
Example :
struct Patient
{
float height;
int weight;
int age;
3
};
struct Patient p1 = { 180.75 , 73, 23 }; //initialization
or,
struct patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;
There are two types of operators used for accessing members of a structure.
Nested structure in C is nothing but structure within structure. One structure can be
declared inside other structure. We can take any data type for declaring structure
members like int, float, char etc. In the same way we can also take object of one structure
as member in another structure.
Example:
struct student
{
char[30] name;
int age;
struct address
{
char[50] locality;
char[50] city;
int pincode;
};
};
Program : The following program is an example of nested structure in
c #include <stdio.h>
#include <string.h>
struct student_college_detail
{
int college_id;
char college_name[50];
};
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data;
int main()
{
struct student_detail stu_data = {1, \”sai”, 90.5, 1110,”sv University”};
printf(“ Id is: %d \n”, stu_data.id);
printf(“ Name is: %s \n”, stu_data.name);
printf(“ Percentage is: %f \n\n”, stu_data.percentage);
printf(“ College Id is: %d \n”, stu_data.clg_data.college_id);
printf(“ College Name is: %s \n”, stu_data.clg_data.college_name);
return 0;
}
Output :
Id is: 1
Name is: sai
Percentage is: 90.50000
College id is: 1110
College name is: Sv University
It is also possible to create structure pointers. We can also create a pointer, pointing to
structure elements.
For this we require “->” operator.
For example:
struct student *p; // p is a pointer variable to structure
P=&s1; //making pointer ‘p’ to s1
Now the expression “*p” accesses the total memory of “s1” The expression “(*p).id”
accesses the “id” in s1.
The expression “(*p).id” is equal to “p -> id”
The expression “(*p).name” accesses the “name” in s1.
“(*p).name” is equal to “p -> name”
Program : The following program is an example of a pointer to a structure.
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
void printBook( struct Books *book );
int main( )
{
struct Books Book1; //Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
If incase, the
structure of object or any element of struct are not initialized, the compiler will automatically
assigned zero to the fields of that particular record.
Example :
employee data [3] = { { 146,’m’} ,{ 200, ‘f’ },{250 ,’m’}};
Compiler will assign :
data [0].sal=0; data [1].sal=0; data [2].sal=0;
Program :The program to initialize the array of structure members & display
#include<stdio.h>
void main ()
{
int i;
struct student
{
long int rollno;
char sex;
float height;
float weight;
};
struct student data [3] = { {121,’m’,5.7,59.8},{122,’f’,6.0,65.2},{123,’m’, 6.0, 7.5} };
clrscr ();
printf (“the initialized contents are:\n”);
for ( i=0; i< =2; i++)
{
printf (“%d/n ** Record is \n “, data [i].rollno);
printf (“%c\n“, data [i] .sex);
printf (“%f\n”, data [i].height);
printf (“%f\n”, data [i]. weight);
}
}
Output :
Output: The initialized contents are:
121
** Record is
m
5.700000
59.799999
122
** Record is
f
6.00000
65.19997
123
** Record is
m
6.000000
7.500000
When variables are declared memory is allocated to each variable. C provides data manipulation
with addresses of variables therefore execution time is reduced. Such concept is possible with
special data type called pointer. A pointer is a variable which holds the address of another
variable or identifier this allows indirect access of data.
We know that memory is a collection of bits, in which eight-bits constitute one byte. Each byte has
its own unique location number called its “address”. To store this address we need a special kind
of variable called “pointer variable”.
This referencing operator is also called address operator, which gives the address of a variable,
in which location the variable is resided in the memory.
Syntax : &variable-name;
This operator is used to get the value at a given address. For example,*(2020)◊ 10; The
Declaration :
To differentiate ordinary variables from pointer variable, the pointer variable should
proceed by called “value at address operator”. It returns the value stored at particular
address. It is also called an indirection operator (symbol *).
Pointer variables must be declared with its type in the program as ordinary variables. Without
declaration of a pointer variable we cannot use in the program.
A variable can be declared as a pointer variable and it points to starting byte address of
any data type.
IMPORTANT POINTS :
1. A pointer variable can be assigned to another pointer variable, if both are pointing to the
same data type.
2. A pointer variable can be assigned a NULL value.
3. A pointer variable cannot be multiplied or divided by a constant.
Example : p*3 or p/3 where p is a pointer variable
4. C allows us to add integers to or subtract integers from pointers.
Example : p1+4, p2-2, p2-p1
If both p1, p2 are pointers to same way then p2-p1 gives the number of elements between p1, p2
5. Pointer variable can be incremented or decremented p++ & p- -
We can declare a pointer to be of any data type void, and can assign a void pointer to any other
type.
It gives error because the pointer p is of type void and cannot hold any value. So, we have to type
cast the pointer variable from one type to other type.
1. stdio.h
2. alloc.h
3. mem.h
4. stddef.h
5. stdlib.h
Pointer can be used with array for efficient programming. The name of an array itself indicates
the stating address of an array or address of first element of an array.
That means array name is the pointer to starting address or first elements of the array. If A is an
array then address of first element can be expressed as &A[0] or A. The Compiler defines array
name as a constant pointer to the first element.
Pointers and arrays are closely related, the array expressions can be taken as pointer expressions,
for example x[i] can be written as *(x+i)
Hence, the expression “array name” without any index gives the address of first element
which is called base-address of array.
Assuming that the base address of arr is 1000 and each integer requires two byte, the five
elements will be stored as follows
Here variable arr will give the base address, which is a constant pointer pointing to the
element, arr[0]. Therefore arr is containing the address of arr[0] i.e. 1000.
arr is equal to &arr[0] // by default
We can declare a pointer of type int to point to the array arr.
int *p;
p = arr;
or
p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element to
another.
NOTE: You cannot decrement a pointer once incremented.
Program: The following program is an example of pointer arrays.
#include<stdio.h>
#include< conio.h>
void disp (int *, int);
main( )
{
int i, a[10],n;
printf (“ enter the size of an
array:”); scanf (“%d”, &n);
printf (“ enter the array
elements:”); for (i=0; i<n; i++)
scanf (“%d”, &a[i]);
disp (a,n);
printf(“ array elements after sorting ”
); for(i=0;i<n;i++)
printf (“%d”, a[i]);
}
Pointer can also be used to create strings. Pointer variables of char type are treated as string.
Pointers are very useful in accessing character arrays. The character strings can be assigned with
a character pointer.
Example :
char array[ ] = “Love India”; //array version
char *str = "Hello";
This creates a string and stores its address in the pointer variable str. The pointer str now points
to the first character of the string "Hello". Another important thing to note that string created
using char pointer can be assigned a value at runtime.
char *str;
str = "hello"; //Legal
The content of the string can be printed using printf() and
puts(). printf("%s", str);
puts(str);
Notice that str is pointer to the string, it is also name of the string. Therefore we do not need to
use indirection operator *.
Program : The following program is an example of pointer and character array.
#include<stdio.h>
#include<conio.h>
main()
{
int i;
char *p= “ Love India”;
clrscr();
while (*p! = “\0”)
{
printf (“ %c “, *p);
p++;
}
}
Output :
Love India
In a 16 bit machine, size of all types of pointer, be it int*, float*, char* or double* is always 2
bytes. But when we perform any arithmetic function like increment on a pointer, changes occur as
per the size of their primitive data type.
Consider an int type ptr as follows :
Assume that it is allotted the memory address 65494 increment value by 1 as follows.
++ and -- operators are used to increment, decrement a ptr and commonly used to move the ptr to
next location. Now the pointer will refer to the next location in the memory with address 65496.
C language automatically adds the size of int type (2 bytes) to move the ptr to the next memory
location.
mptr = mtpr + 1
= 65494 + 1 * sizeof (int)
= 65494 + 1 * 2
Similarly an integer can be added or subtract to move the pointer to any location in RAM. But the
resultant address is dependent on the size of data type of ptr.
The step in which the ptr is increased or reduced is called scale factor. Scale factor is nothing but
the size of data type used in a computer.
We know that, the size of
float = 4
char = 1
double = 8 and so on
A program in C language involves into different processes. Below diagram will help you to
understand all the processes that a C program comes across.
∙ First region – This is the memory region which holds the executable code of the
program.
∙ 2 region – In this memory region, global variables are stored. ∙
nd
3rd region – stack
∙ 4th region – heap
5.3.2. Difference Between Stack & Heap Memory
Stack Heap
Compiler reads the entire source Interpreter reads the program source
code of the program and converts it code one line at a time and executing
into binary code. This process is that line. This process is called
called compilation. interpretation.
∙ #define – This macro defines constant value and can be any of the basic data types. ∙
#include <file_name> – The source code of the file “file_name” is included in the main C
program where “#include <file_name>” is mentioned.
#include <stdio.h>
void main()
OUTPUT:
value of letter : A
value of backslash_char : ?
Example Program for Conditional Compilation Directives: A) EXAMPLE
PROGRAM FOR #IFDEF, #ELSE AND #ENDIF IN C:
“#ifdef” directive checks whether particular macro is defined or not. If it is defined, “If”
clause statements are included in source file.
Otherwise, “else” clause statements are included in source file for compilation and
execution.
#include <stdio.h>
int main()
#ifdef RAJU
"this C file\n");
#else
#endif
return 0;
OUTPUT:
#ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined, “If”
clause statements are included in source file.
Otherwise, else clause statements are included in source file for compilation and execution.
#include <stdio.h>
int main()
#ifndef SELVA
"define here\n");
#else
#endif
return 0;
OUTPUT:
“If” clause statement is included in source file if given condition is true. Otherwise, else
clause statement is included in source file for compilation and execution.
#include <stdio.h>
#define a 100
int main()
{
#if (a==100)
"a \= 100\n");
#else
#endif
return 0;
OUTPUT:
#include <stdio.h>
void main()
OUTPUT:
First defined value for height : 100
Pragma is used to call a function before and after main function in a C program.
#include <stdio.h>
void function1( );
void function2( );
#pragma startup function1
#pragma exit function2
int main( )
return 0;
void function1( )
void function2( )
OUTPUT: