PPSC Unit IV (18-1-23)
PPSC Unit IV (18-1-23)
UNIT-4
POINTERS
POINTER: A pointer is a variable that stores/points the address of another variable. A Pointer in C is
used toallocate memory dynamically i.e. at run time. The pointer variable might be belonging to any of
the data type such as int, float, char, double, short etc.
Pointer Syntax : data_type *var_name;
Example : int *p; char *p;
Where, * is used to denote that “p” is pointer variable and not a normal variable.
Example 2:
#include <stdio.h>
int main ()
{
int var; int *ptr;
int **pptr; var = 3000; // take the address of var
ptr = &var; // take the address of ptr using address of operator &
pptr = &ptr; // take the value using pptr
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}
Output: Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
Example 3:
#include<stdio.h>
void main ()
{
int a = 10;
int *p;
int **pp;
p = &a; // pointer p is pointing to the address of a
pp= &p; // pointer pp is a double pointer pointing to the address of pointer p
printf ("address of a: %x\n",p); // Address of a will be printed
printf("address of p: %x\n",pp); // Address of p will be printed
printf("value stored at p: %d\n",*p); // value stored at the address contained by p i.e. 10 will be
printed
printf("value stored at pp: %d\n",**pp); // value stored at the address contained by the pointer
stored at pp
}
Output : address of a: d26a8734address of a: d26a8734
Value is 10 address of p: d26a8738
value stored at p: 10
value stored at pp: 10
Pointer Compatibility:
//single Pointer with multiple variables
#include<stdio.h>
int main()
{
int a,b,c,*p; //a,b and c are variables and p is a pointerprintf("Enter three integers : ");
scanf("%d %d %d",&a,&b,&c);
p = &a;
printf("pointer points to a. Value is %d\n",*p);
p = &b;
printf("pointer points to b. Value is %d\n",*p);
p = &c;
printf("pointer points to c. Value is %d\n",*p);
return 0;
}
Output:
Enter three integers : 10
20
30
pointer points to a. Value is 10
pointer points to b. Value is 20
pointer points to c. Value is 30
//single variable with multiple Pointers
#include<stdio.h>
int main()
{
a,*p,*q,*r; //a,b and c are variables and p is a pointer
printf("Enter a integer: ");
scanf("%d",&a);
p = &a;
printf("pointer points to a. Value is %d\n",*p);
q = &a;
printf("pointer points to b. Value is %d\n",*q);
r = &a;
printf("pointer points to c. Value is %d\n",*r);
return 0;
}
Output:
Enter a integer: 10
pointer points to a. Value is 10
pointer points to b. Value is 10
Lvalue and R Value: In C, an expression is either lvalue or anrvalue. every expression has a value.
But the value in an expression can be used in two different ways.
1. An lvalue expression must be used whenever the object is receiving a value.
2. An rvalue expression can be used to supply a value for further use.
Only 7 types of expressions are Lvalue expressions, they are given in below table
Pointer applications:
It is a strong relationship between pointers and arrays, strong enough that pointers and arrays should
be discussed simultaneously. Any operation that can be achieved by array subscripting can also be
done with pointers.
The declaration int a[10]; defines an array of size 10, that is, a block of 10 consecutive objects
named a[0], a[1], ...,a[9]. The notation a[i] refers to the ith element of the array. If pa is a pointer to
an integer, declared as int *pa; then theassignment
pa = &a[0]; sets pa to point to element zero of a; that is, pa contains the address of a[0].
pa = &a[0]; pa and a have identical values. Since the name of an array is a synonym for the location
of the initial element, the assignment pa=&a[0] can also be written as In evaluating a[i], C converts
it to *(a+i) immediately; the two forms are equivalent.
Applying the operator & to both parts of this equivalence, it follows that &a[i] and a+i are also
identical: a+i is the address of the ith element beyond a. As the other side of this coin, if pa is a
pointer, expressions might use it with a subscript; pa[i] is identical to
*(pa+i). In short, an array-and-index expression is equivalent to one written as a pointer and offset
Incrementing Pointer variable : To display the value stored in an array without using any index value.
Then Pointer will help you toget there by using increment operator.
Output: 10 11 12
Decrementing Pointer Variable: Like increment, we can decrement a pointer variable. The formula of
decrementing pointer is given below:
new_address= current_address - i * size_of(data type)
Comparing Pointer Variable: Pointer variable can be compared either with other pointer variable or
with normal variable. Relational operators will get you there for comparison operation. Let us using
greater than operatorto compare two pointer variables.
enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language
is possible by 4 functions of stdlib.h header file.
1. malloc()
2. calloc()
3. realloc()
4. free()
Before learning above functions, let's understand the difference between static memory allocation
and dynamic memory allocation.
1. malloc(): The malloc() function allocates single block of requested memory in bytes. It doesn't initialize
memory at execution time, so it has garbage value initially.Itreturns NULL if memory is not sufficient.
Syntax: ptr=(cast-type*)malloc(byte-size);
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,*ptr,sum=0;
printf("Elements of array: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using mallocif(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("\nEnter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("\nSum=%d",sum); free(ptr);
return 0;
}
Output:
Elements of array: 3 Enter
elements of array: 21
3
Sum=6
calloc(): The calloc() function allocates multiple block of requested memory. It initially initialize all
bytes to zero. It returns NULL if memory is not sufficient.
realloc(): If memory is not sufficient for malloc() or calloc(), you can reallocate the memory byrealloc()
function. In short, it changes the memory size.
Example:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p, i, n;
printf("Initial size of the array is 4\n\n");p
= (int*)calloc(4, sizeof(int));
if(p==NULL)
{
printf("Memory allocation failed");
exit(1); // exit the program
}
for(i = 0; i< 4; i++)
{
printf("Enter element at index %d: ", i);
Final array: scanf("%d", p+i);
}
printf("\nIncreasing the size of the array by 5 elements ...\n ");
p = (int*)realloc(p, 9 * sizeof(int));
if(p==NULL)
{
printf("Memory allocation failed");exit(1); // exit the program
}
printf("\nEnter 5 more integers\n\n");
for(i = 4; i< 9; i++)
{
printf("Enter element at index %d:
", i);scanf("%d", p+i);
}
printf("\nFinal array: \n\n");
for(i = 0; i< 9; i++)
{
printf("%d ", *(p+i) );
}
// signal to operating system program ran fine
return 0;
}
Output:
Enter element at index 0: 11
Enter element at index 1: 33
Enter element at index 2: 22
Enter element at index 3: 55
Increasing the size of the array by 5 elements ...
Enter 5 more integers
Enter element at index 4: 99
Enter element at index 5: 77
Enter element at index 6: 88
Enter element at index 7: 66
Enter element at index 8: 44
11 33 22 55 99 77 88 66 44
Example 2:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int)*2);
int i;
int *ptr_new;
*ptr = 10;
*(ptr + 1) = 20;
ptr_new = (int *)realloc(ptr, sizeof(int)*3);
*(ptr_new + 2) = 30;
for(i = 0; i< 3; i++) printf("%d ", *(ptr_new + i));
return 0;
}
Output:
10 20 30
4. free(): free () function frees the allocated memory by malloc (), calloc (), realloc () functions and
returns the memory to the system.
Syntax: free(ptr);
Array of pointers: “Array of pointers” is an array of the pointer variables. It is also known as pointer
arrays.
Syntax: int*var_name[array_size];
Declaration of an array of pointers: int *ptr[3];
We can make separate pointer variables which can point to the different values or we can make one
integer array of pointers that can point to all the values.
}
Output:
Enter elements: 3
4
2
6
1
You entered:
3
4
2
6
Types of Pointers : There are four different types of pointers which are as follows −
Null pointer
Void pointer
Wild pointer
Dangling pointer
Null Pointer: A Null Pointer is a pointer that does not point to any memory location. It stores the base
address of the segment. The null pointer basically stores the Null value while void is the type of the
pointer. This method is useful when you do not assign any address to the pointer. A null pointer
always contains value 0.
//Example Program
#include <stdio.h>
int main()
{
int *ptr = NULL; //null pointer
printf("The value inside variable ptr is:%d",ptr);
return 0;
}
Output:
Void Pointer: It is a pointer that has no associated data type with it. A void pointer can hold addresses
of any type and can be typecast to any type. It is also called a generic pointer and does not have any
standard data type. It is created by using the keyword void.
\
// C program for the void pointer
#include <stdio.h>
int main()
{
void *p = NULL; //void pointer
printf("The size of pointer is:%d",sizeof(p)); //size of p depends on compiler
return 0;
}
Output:
The size of pointer is: 8
Wild Pointer: Pointers store the memory addresses. Wild pointers are different from pointers i.e. they
also store the memory addresses but point the unallocated memory or data value which has been
deallocated. Such pointers are known as wild pointers.
//Example:
#include <stdio.h>
int main()
{
int *p; //wild pointer
printf("%d",*p);
return 0;
}
Output:
Process returned -1073741819 (0xC0000005) execution time : 1.206 s
In the above program, a pointer arr is declared but not initialized. So, it is displaying some random
memory locations.
Dangling pointer: Dangling pointer is a pointer pointing to a memory location that has been freed (or
deleted). Thereare different ways where Pointer acts as dangling pointer.
//Example
#include <stdio.h>
int main()
{
int *show(void)
{
int n = 76; /* ... */ return &n;
}
Output: Output of this program will be garbage address.
De-allocation of memory
#include <stdio.h>
int main()
{
float *p = (float *)malloc(sizeof(float)); //dynamic memory allocation.
free(p); //after calling free()
//p becomes a dangling pointer
p = NULL; //now p no more a dangling pointer.
}
Variable goes out of scope:
#include <stdio.h>
int main()
{
int *p //some code/
{
int c;
p=&c;
}
//some code
//p is dangling pointer here.
}
Preprocessor Directives: Before a C program is compiled in a compiler, source code is processed by a
program calledpreprocessor. This process is called preprocessing. Commands used in preprocessor are
called preprocessor directives. They are never terminated with a semicolon(;).
1
2
3
4
5
#define example 1:
#include <stdio.h>
#define PI 3.14
main()
{
printf("%f",PI);
}
Output: 3.140000
//Example 2
#include <stdio.h>
#define height 100
#define number 3.14
#define letter 'A' void
main()
{
printf("value of height : %d \n", height);
printf("value of number : %f \n", number);
printf("value of letter : %c \n", letter);
}
Output: value of height: 100
value of number: 3.140000
value of letter: A
FOR #IF, #ELSE AND #ENDIF: “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.
//Example Program
#include <stdio.h>
#define a 100
int main()
{
#if (a==100)
printf("This line will be added = 100\n");#else
printf("This line will be added is not equal to 100\n");
#endif
return 0;
}
OUTPUT:
This line will be added in this C file since a = 100
//Example on #else
#include <stdio.h>
#include <conio.h>
#define NUMBER 1
void main()
{
#if NUMBER==0
printf("Value of Number is: %d", NUMBER);
#else
printf("Value of Number is non-zero");
#endif
getch();
}
Output:
Value of Number is non-zero
UNDEF : This directive undefines existing macro in the program.
//Example for #undefine
#include <stdio.h>
#define PI 3.14
#undef PI
main()
{
printf("%f",PI);
}
Output : Compile Time Error: 'PI' undeclared
//Example 2:
#include <stdio.h>
#define height 100
void main()
{
printf("First defined value for height : %d\n",height);
#undef height // undefining variable
#define height 600 // redefining the same for new value
printf("value of height undef \& redefine:%d",height);
}
OUTPUT: First defined value for height : 100
value of height after undef& redefine : 600
Example 3:
#include <stdio.h>
#define number 15
int square=number*number;
#undef number
main()
{
printf("%d",square);
}
Output: 225
//Example Program to call a function before and after main function in a C program.
#include<stdio.h>
int main()
{
printf("File :%s\n",FILE );
printf("Date :%s\n", DATE);
printf("Time :%s\n", TIME );
printf("Line :%d\n", LINE );
printf("STDC :%d\n",STDC );
return 0;
}
Output: File :program examle.c
Example 2:
#include <stdio.h>
void function1( );
void function2( );
#program startup function1
#program exit function2
int main( )
{
printf ( "\n Now we are in main function" ) ;
return 0;
void function1( )
{
printf("\nFunction1 is called before main function call");
}
void function2( )
{
printf ( "\nFunction2 is called after main function call”);
}
}
Output: Function1 is called before main function call
//Now we are in main function
Function2 is called just before end of main function
Exercise Programs
1. Program to create, initialize, assign and access a pointer variable.
2. Program to swap two numbers using pointers.
3. Program to change the value of constant integer using pointers.
4. Program to print a string using pointer.
5. Program to count vowels and consonants in a string using pointer.
6. Program to read array elements and print with addresses.
7. Program to read and print student details using structure pointer, demonstrate example of structure
with pointer.
8. Program to print size of different types of pointer variables.
9. Program to demonstrate example of double pointer (pointer to pointer).
10. Program to demonstrate example of array of pointers.
11. An Example of Null pointer in C
12. Making a valid pointer as NULL pointer in C
13. Modify value stored in other variable using pointer in C
Assignment 4
Q.No. Questions BTL CO
SET - 1
1 What is pointer? Explain how the pointer variable declared and initialized? K2 CO4
Explain the following Dynamic Memory Allocation functions in C malloc(),
2 K2 CO4
calloc(), free() and realloc()
3 Write a program using pointers to swap two numbers. K3 CO4
SET - 2
1 Explain about pointer to pointer with an example K2 CO4
2 List and explain the valid operations that are performed on pointers. K2 CO4
3 Write a C program using pointers to add two numbers using pointers. K3 CO4
SET - 3
1 Define pointer. Explain how to declare and use pointers. K2 CO4
2 Differentiate malloc and calloc with suitable example. K2 CO4
Write a C program that access elements of one Dimensional arrayusing a
3 K3 CO4
pointer variable.