Pps Unit 5-Updated
Pps Unit 5-Updated
Unit –V
POINTERS IN C
Suppose compiler has reserved bytes numbered 3527 and 3528 for the storage of variable age and then the address of
variable age will be 3527. Let us assign some value to this variable: age = 20;
Now this value will be stored in these 2 bytes (in binary form). The number of bytes allocated will depend on the data
type of variable.
C provides an address operator '&', which returns the address of a variable when placed before it. This operator can be
read as "the address of ", so &age means address of age, similarly &sal means address of sal. The following program
prints the address of variables using address operator.
Addresses are just whole numbers. These addresses may be different each time you run your program, it depends on
which part of memory is allocated by operating system for this program.
Ques) What do you mean by pointer? How can you declare it and assign address of a variable to a pointer?
A pointer is a variable that stores memory address. Like all other variables it also has a name, has to be declared and
occupies some space in memory. It is called pointer because it points to a particular location in memory by storing the
address of that location.
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023
data_type *pname;
Here pname is the name of pointer variable, which should be a valid C identifier. The asterisk '*' preceding this name
informs the compiler that the variable is declared as a pointer. Here data_type is known as the base type of pointer. Let
us take some pointer declarations-
int *iptr;
float *fptr;
char *cptr, chI, ch2;
Here iptr is a pointer that should point to variables of type int, similarly fptf and cptr should point to variables of float
and char type respectively.
Now both pointer variables iptr and p1 contain the address of variable age and point to the same variable age
We can also access a variable indirectly using pointer. For this we will use the indirection operator (*). By placing the
indirection operator before a pointer variable, we can access the variable whose address is stored in the pointer.
Example:
int a = 87
float b= 4.5;
int *p1 = &a;
float *p2 = &b;
In our program, if we place'*’ before p1 then we can access the variable whose address is stored in p1. Since p1 contains
the address of variable a, we can access the variable a by writing *p1. Similarly we can access variable b by writing *p2.
So we can use *p1 and *p2 in place of variable names a and b anywhere in our program.
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023
/*Program to print the size of pointer variable and size of value dereferenced by that pointer* /
#include<stdio.h>
main ( )
(
char a= 'x' , *p1=&a;
int b=12, *p2=&b;
float c=12.4,*p3=&c;
double d=18.3,*p4=&d;
printf("sizeof(p1) = %d , sizeof(*p1) = %d\n”,sizeof(p1),sizeof(*p1));
printf("sizeof(p2) =%d , sizeof(*p2) = %d\n”,sizeof(p2),sizeof(*p2));
printf("sizeof(p3) =%d , sizeof(*p3) = %d\n”,sizeof(p3),sizeof(*p3));
printf ("sizeof(p4) =%d , sizeof(*p4) = %d\n”,sizeof(p4),sizeof(*p4));
}
Output:
sizeof(p1) = 2 , sizeof(*p1) = 1
sizeof(p2) = 2 , sizeof(*p2) = 2
sizeof(p3) = 2 , sizeof(*p3) =4
sizeof(p4) = 2 , sizeof(*p4) =8
POINTER ARITHMETIC
All types of arithmetic operations are not possible with pointers. The only valid operations that can be performed are as-
Here all arithmetic is performed relative to the size of base type of pointer. For example if we have an integer pointer pi
which contains address1000 then on incrementing we get 1002 instead of 1001. This is because the size of int data type
is 2. Similarly on decrementing pi, we will get 998 instead of 999. The expression (pi+3) will represent the address 1006.
Let us see some pointer arithmetic for int, float and char pointers.
Suppose the address of variables a, b and c are 1000, 4000, 5000 respectively, so initially values of p1, p2, p3 will be
1000, 4000 and 5000.
Output:
Value of pi = Address of a = 1000
Value of pc =Address of b = 4000
Value of pf = Address of c = 8000
Now value of pi = 1002
Now value of pc = 4001
Now value of pf = 8004
/*Program to understand the postfix/prefix increment/decrement in a pointer variable of base type int */
#include<stdio.h>
main()
{
int a=5;
int *p;
p=&a;
printf ("Value of p =Address of a= %u\n",p);
printf ("Value of P =%u\n",++p);
printf ("Value of p = %u\n",p++);
printf ("Value of p = %u\n",--p);
printf ("Value of p = %u\n",p--);
printf ("Value of p = %u\n",p);
}
Output:
Value of p = Address of a = 1000
Value of p = 1002
Value of p = 1002
Value of p = 1002
Value of p = 1002
Value of p = 1000
Subtraction of a pointer from another pointer of same base type returns an integer, which denotes thenumber of
elements between two pointers. If we have two int pointers ptr1 and ptr2, containing addresses 3000 and 3010
respectively then ptr2 – ptr1 will give 5. (since size of int is 2). This operation is generally performed when both pointer
variables point to the elements of same array.
More Questions:
1. Write a note on pointer arithmetic with proper example in C language.
VOID POINTER
void Pointers: We have studied that a pointer should be assigned an address of the same type as mentioned in pointer
declaration. For example if we have a pointer to int, then it would be incorrect to assign the address of a float variable to
it. But an exception to this rule is a pointer to void. A pointer to void is a generic pointer that can point to any data type.
The syntax of declaration of a void pointer is
void *vp;
We can assign address of any data type to a void pointer and a void pointer can be assigned to a pointer of any data
type.
OR
What are the problems in static memory allocation? How can we resolve it?
An array is a collection of fixed number of values of a single type. That is, you need to declare the size of an array before
you can use it.
Sometimes, the size of array you declared may be insufficient. To solve this issue, you can allocate memory manually
during run-time. This is known as dynamic memory allocation in C programming.
There are 4 library functions defined under <stdlib.h> makes dynamic memory allocation in C
programming. They are malloc(), calloc(), realloc() and free().
malloc(): The name "malloc" stands for memory allocation.The malloc() function reserves a block of memory of the
specified number of bytes. And, it returns a pointer of type void which can be casted into pointer of any form.
Syntax of malloc():
ptr = (cast-type*) malloc(byte-size)
Example:
Considering the size of int is 4 bytes, this statement allocates 400 bytes of memory. And, the pointer ptr holds the
address of the first byte in the allocated memory. However, if the space is insufficient, allocation fails and returns a NULL
pointer.
calloc(): The name "calloc" stands for contiguous allocation.The malloc() function allocates a single block of memory.
Whereas, calloc() allocates multiple blocks of memory and initializes them to zero.
Syntax of calloc():
This statement allocates contiguous space in memory for 25 elements each with the size of float.
free(): Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on their own. You must
explicitly use free() to release the space.
This statement frees the space allocated in the memory pointed by ptr.
This program calculates the sum of n numbers entered by the user. To perform this task, calloc() and free() is used.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023
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;
}
realloc(): If the dynamically allocated memory is insufficient or more than required, you can change the size of
previously allocated memory using realloc() function.
Syntax of realloc():
ptr = realloc(ptr, x);
In this case, variables get allocated permanently In this case, variables get allocated only if your
program unit gets active
Allocation is done before program execution Allocation is done during program execution
It uses the data structure called stack for It uses the data structure called heap for
implementing static allocation implementing dynamic allocation
More Questions:
1. Explain dynamic memory allocation and various functions for dynamic memory allocation, with suitable examples.
Write a program to create an array dynamically and print the sum of its elements.
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023
LINKED LIST
Linked Lists:
A linked list is a dynamic data structure where each element (called a node) is made up of two items - the data and a
reference (or pointer) which points to the next node. A linked list is a collection of nodes where each node is connected
to the next node through a pointer. The first node is called a head and if the list is empty then the value of head is NULL.
More Questions:
1.What is linked list? Write the self referential structure of a node in linked list? In which situation array is advantageous
over linked list?
FILE HANDLING IN C
A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent
storage of data. It is a readymade structure. In C language, we use a structure pointer of file type to declare a file.
FILE *fp;
How to achieve File Handling in C: For achieving file handling in C we need follow following steps
Naming a file
Opening a file
Reading data from file
Writing data into file
Closing a file
C provides a number of functions that helps to perform basic file operations. Following are the functions
To write an integer in
6 putw() putw(integer, fp)
file.
Opening or creating file: Before opening any file we need to specify for which purpose we open file, for example file
open for write or read purpose.
pf=fopen("filename", "mode");
For opening a file, fopen function is used with the required access modes. Some of the commonly used file access modes
are mentioned below.
“r” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points
to the first character in it. If the file cannot be opened fopen( ) returns NULL.
“w” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created.
Returns NULL, if unable to open file.
“a” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points
to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
“r+” – Searches file. If is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the
first character in it. Returns NULL, if unable to open the file.
“w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created.
Returns NULL, if unable to open file.
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023
“a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which
points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
Closing a File: A file must be closed after completion of all operation related to file. For closing file we
need fclose() function.
Syntax: fclose(Filepointer);
Ques) Write a C Program to Count chars ,spaces ,tabs and newlines in a file.
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
int nol=0,not=0,nos=0,noc=0;
fp=fopen(“A.txt”,”r”);
while(1)
{
ch=fgetc(fp);
if(ch==EOF)
break;
noc++;
if(ch==’ ‘)
nos++;
if(ch==’\n’)
nol++;
if(ch==’\t’)
not++;
}
fclose(fp);
printf(“\n Number of characters = %d”,noc);
printf(“\n Number of blanks = %d”,nos);
printf(“\n Number of tabs = %d”,not);
printf(“\n Number of lines = %d”,nol); }
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fptr1, *fptr2;
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023
char c;
fclose(fptr1);
fclose(fptr2);
return 0;
}
More Questions:
1. What are the different file opening modes in C?
2.List out various file operations and modes in C. Write a program to copy the content from one file to another file.
3.What is the significance of EOF in file handling?
4.Write a program to count number of characters, newlines, words, spaces in a file.
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023
PREPROCESSORS IN C
If the source code is stored in a file PR1.C then the expanded source code gets stored in a file PR1.I.
When this expanded source code is compiled the object code gets stored in PR1.OBJ.
When this object code is linked with the object code of library functions the resultant executable code gets stored in
PR1.EXE.
The preprocessor offers several features called preprocessor directives. Each of these preprocessor directives begin with
a #. The directives can be placed anywhere in a program but are most often placed at the beginning of a program,
before the first function definition.
We would learn the following preprocessor directives here:
#define PI 3.1415
main( )
{
float r = 6.25 ;
float area ; area = PI * r * r ;
printf ( "\nArea of circle = %f", area ) ;
}
UPPER and PI in the above programs are often called ‘macro templates’, whereas, 25 and 3.1415 are called their
corresponding ‘macro expansions’.
Macros with Arguments : Macros can have arguments, just as functions can.
Example:
#define AREA(x) ( 3.14 * x * x )
main( )
{ float r1 = 6.25, r2 = 2.5, a ;
a = AREA ( r1 ) ;
printf ( "\nArea of circle = %f", a ) ;
a = AREA ( r2 ) ;
printf ( "\nArea of circle = %f", a ) ;
}
output: Area of circle = 122.656250
Area of circle = 19.625000
In this program wherever the preprocessor finds the phrase AREA(x) it expands it into the statement ( 3.14 * x * x ).
However, that’s not all that it does. The x in the macro template AREA(x) is an argument that matches the x in the macro
expansion ( 3.14 * x * x ). The statement AREA(r1) in the program causes the variable r1 to be substituted for x. Thus the
statement AREA(r1) is equivalent to: ( 3.14 * r1 * r1 ).
After the above source code has passed through the preprocessor, what the compiler gets to work on will be this:
main( )
{ float r1 = 6.25, r2 = 2.5, a ;
a = 3.14 * r1 *r1 ;
printf ( "Area of circle = %f\n", a ) ;
a = 3.14 *r2 * r2 ;
printf ( "Area of circle = %f", a ) ;
}
In a macro call the preprocessor replaces the macro template with its macro expansion. while in a function call
the control is passed to a function along with certain arguments, some calculations are performed in the
function and a useful value is returned back from the function.
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023
Usually macros make the program run faster but increase the program size, whereas functions make the
program smaller and compact. If we use a macro hundred times in a program, the macro expansion goes into
our source code at hundred different places, thus increasing the program size.
if a function is used, then even if it is called from hundred different places in the program, it would take the
same amount of space in the program. But passing arguments to a function and getting back the returned value
does take time and would therefore slow down the program. This gets avoided with macros since they have
already been expanded and placed in the source code before compilation.
Conclusion: Use macro for less number of statements and use function for large number of statements in
function body.
File Inclusion:
Actually there exist two ways to write #include statement. These are:
#include "filename"
#include < filename >
#include< goto.c >: This command would look for the file goto.c in the specified list of directories only.
Example:
#ifdef macroname
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023
statement 1 ;
statement 2 ;
statement 3 ;
#endif
If macroname has been #defined, the block of code will be processed as usual; otherwise not.
#else
statement 4 ;
statement 5 ;
statement 6 ;
#endif
}
#undef Directive: In order to undefine a macro that has been earlier #defined, the directive, #undef macro template can
be used. Thus the statement,
#undef PENTIUM
would cause the definition of PENTIUM to be removed from the system. All subsequent
#ifdef PENTIUM statements would evaluate to false. In practice seldom are you required to undefined a macro, but for
some reason if you are required to, then you know that there is something to fall back upon.
More Questions:
1.Explain the role of the C pre-processor.
2.What is Macros? How is it substituted? Also explain macro act as a variable and macro act as a function with the help of
example.
3.Write macro definition with arguments for calculation of simple interest and amount.
4.Write a short note on with (i) Macro Expansion (ii) File Inclusion (iii) conditional compilation with example.
5.How macro is different from a constant?
6.What is the difference between following directives?
#include<stdio.h> and #include "stdio.h"
7.Differentiate between function and macro.
It is possible to pass some values from the command line to your C programs when they are executed. These values are
called command line arguments.
The command line arguments are handled using main() function arguments where argcrefers to the number of
arguments passed, and argv[] is a pointer array which points to each argument passed to the program. Following is a
simple example which checks if there is any argument supplied from the command line and take action accordingly −
#include <stdio.h>
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
Meerut Institute of Technology, Meerut
Programming for problem Solving (BCS101/BCS201)
Lecture Notes (UNIT-5) Ver.1 2023
#include <stdio.h>
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with a single argument separated by space but inside double quotes, it
produces the following result.
$./a.out "testing1 testing2"