C Programming Unit – V
Introduction to Pointers
Pointer is one of the derived data type in C. Pointer is a variable which is used to
store the address of another variable. it can be created using “*” symbol. A
pointer can point to a variable of same data type. It always points to some
memory location so it is called pointer variable.
Declaring a pointer variable
Declaring a pointer variable means creating a variable that can store the
address of another variable. In C, every variable must be declared before they
are used. The pointer variables contains address of same type of variable.
The syntax for declaring a pointer variable is as follows
data type *ptr_name;
For example,
Char *ch; //pointer to character variable
int *p; //pointer to integer variable
float *f; //pointer to float variable
double *d; //pointer to double variable
here the variables ch, p, f, d are pointer variables. The type int refers to the data
type of the variable being pointed by p.
Note :- The size of any pointer variable is only 8 bytes.
Address Operator ( & )
The address operator (&) extracts the address for a variable. The address
operator syntax is as follows.
&VariableName;
Page 1
C Programming Unit – V
Ex: to know the address of the variable n, just use ”&n”
Here &a = 100 (address of variable a)
&b = 200 (address of variable b)
The & operator can be used only with a simple variable or with an
element of the array. If x is an array then expressions such as &x[0], &x[3] are
valid and represent the addresses of 0th and 3rd elements of array x.
The following are illegal use of address operator
a) &125 (pointing at constants)
b) int x[10];
&x (pointing at arrays)
c) &(x+y) (pointing at expressions)
Indirection Operator (*) (or)
Dereferencing operator (or)
Value at address operator
It is called as ‘Value at address’ operator. It is also known as
Dereferencing Operator. It returns the value stored at address assigned
to a pointer variable.
Once a pointer is assigned with address of a variable, pointer is de-
referenced to access the value of the variable using indirection operator or
de-referencing operator i.e *.
Page 2
C Programming Unit – V
Here *b = 10 (value at address 100)
*a = not applicable because “a” can not store address.
L-value and R-value
Understanding L-value and R-value is important for working with
variables and pointers in C.
L-value (Local value) refers to a memory location that can appear
on the left side of an assignment.
L-Value is “variable” or an “object” whose value can change.
R-value (Read value) refers to a data value that appears on the
right side of an assignment. R=value is a temporary value,
literal, or value that does NOT have memory location.
A pointer variable itself is an L-value, because it has an address and
can be assigned a new value.
int *p; // p is a pointer (L-value)
int x = 5;
p = &x;
p is an L-value (it can appear on the left of =).
&x is an R-value (value being assigned — the address of x).
Expression Acts As Meaning
x = 10; L = x, R = 10 Variable x stores value 10
p = &x; L = p, R = &x Pointer p stores address of x
*p = 20; L = *p, R = 20 Value at address in p is changed
y = *p; L = y, R = *p y gets value stored at pointer p
Page 3
C Programming Unit – V
Pointer Arithmetic or Address Arithmetic :
Pointer arithmetic means performing arithmetic operations like addition,
subtraction, etc., on pointers. It allows traversal and manipulation of memory
locations efficiently.
Valid Pointer Operations in C:
1. Addition (ptr + n)
Moves pointer forward by n elements.
Example :
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr;
printf("%d", *(ptr + 2)); // Output: 30
Here, ptr + 2 moves to the 3rd element (2 positions ahead).
2. Subtraction (ptr - n)
Moves the pointer backward by n elements.
Example :
int *p = &arr[3]; // pointing to 4th element
printf("%d", *(p - 2)); // Output: 20
3. Pointer Difference (ptr1 - ptr2)
Returns the number of elements between two pointers.
Example :
int *p1 = &arr[4];
int *p2 = &arr[1];
int diff = p1 - p2; // diff = 3
4. Increment (ptr++) and Decrement (ptr--)
ptr++: Moves pointer to the next element.
Example:
Page 4
C Programming Unit – V
int arr[5]={10,20,30,40,50};
int *p = arr;
p++; // Now p points to arr[1]
ptr--: Moves pointer to the previous element.
Example:
int arr[5]={10,20,30,40,50};
int *p = arr[2];
p--; // Now p points to arr[1]
Invalid Pointer Operations (Not Allowed):
Adding two pointers: p1 + p2 is not allowed.
Multiplying/dividing pointers is not allowed.
Pointers to pointers or double pointer
When one pointer variable store the address of another pointer variable, then this
is called double pointer or pointer to pointer or multiple indirection. This is
illustrated in the following figure.
In pointers to pointers, first pointer contains the address of the second
pointer which points to the variable that contains the desired value.
A variable that is a pointer to a pointer must be declared first. The general form
of declaring pointer to pointer is
Syntax:
datatype **pointer_name;
ex:
int var1 = 10;
int *ptr1 = &x; // p holds address of x
int **ptr2 = &p; // pp holds address of p
Page 5
C Programming Unit – V
Here
Variable Value Points to
var1 10 --
ptr1 &var1 var1
ptr2 &ptr1 ptr1
Accessing Values:
printf("%d", x); // print 10 (value of X)
printf("%d", *p); // 10 (value of x)
printf("%d", **pp); // 10 (value of x)
Array of Pointers
An array of pointers is similar to an array of char or int or float or double. Here
each element is a pointer. An array of pointers is a collection of addresses.
Syntax:
data_type *array_name[size];
Example: int *arrop[3];
here the variable “arrop” is an array of 3 pointers. In this case, we can
store 3 different integer addresses to this array variable. Elements of the array
may contain different addresses.
Example Program:
#include<stdio.h>
int main()
{
int *arrop[3]; //array of pointers
int a = 10, b = 20, c = 50, i;
arrop[0] = &a;
arrop[1] = &b;
arrop[2] = &c;
Page 6
C Programming Unit – V
for(i = 0; i < 3; i++)
printf("Address = %d\t Value = %d\n", arrop[i], *arrop[i]);
}
Pointer to an array
A pointer to an array is a pointer that holds the address of an entire
array, not just a single element.
Syntax :
type *ptr= array;
type → data type of array elements
ptr → pointer to the entire array
Example :
#include<stdio.h>
int main()
{
int arr[5]={10,20,30,40,50};
int *p=a;
int i;
for( i=0;i<5;i++)
printf("%d ",*(p+i));
return 0;
}
Explanation :
Page 7
C Programming Unit – V
int *p=arr → declares p as a pointer to an array.
*(p+i) → accesses elements of the array through the pointer.
Function Pointer
A function pointer is a pointer that points to a function instead of a
variable. It allows you to call functions dynamically or pass functions as
arguments to other functions.
Syntax:
return_type (*pointer_name)(parameter_list);
example :
#include <stdio.h>
// A simple function
void greet()
{
printf("Hello, World!\n");
}
int main()
{
// Declare a function pointer
void (*fp)();
// Assign address of function to pointer
fp = greet;
// Call the function using pointer
fp(); // Same as greet();
return 0;
}
Example to pass function as argument to other function.
#include <stdio.h>
Page 8
C Programming Unit – V
void add(int a, int b)
{
printf("Sum: %d\n", a + b);
}
void operate(void (*fptr)(int, int))
{
fptr(10, 20);
}
int main()
{
operate(add); // Passing function as argument
return 0;
}
Parameter passing Technique / Pointers and Functions / Call by value
Vs Call by Reference
Parameter passing is a technique for communication of data between calling
function and the called function. It can be achieved either by passing the value
of the variable (or) by the address of the variable. So C supports two types of
parameter passing techniques. They are
i) Pass by value or Call by value
ii) Pass by address or Call by reference (or Call by address)
Call by value :
The process of calling a function by passing the actual value of variables
is known as call by value. The call by value method of passing arguments to a
function copies the actual value of an parameter into the formal parameter of
the function. In this case, Change of formal parameters in the function will not
affect the actual parameters in the calling function.
Example :
#include<stdio.h>
void swap(int a,int b)
{
int t;
t=a;
a=b;
b=t;
}
void main()
Page 9
C Programming Unit – V
{
void swap(int,int);
int a=10,b=20;
printf("Values before swapping : ");
printf("\na=%d",a);
printf("\nb=%d",b);
swap(a,b);
printf("\nValues after swapping : ");
printf("\na=%d",a);
printf("\nb=%d",b);
}
Output:
Values before swapping :
a=10
b=20
Values after swapping :
a=10
b=20
Call by reference:
The process of calling a function using pointers to pass the addresses of
variables is known as call by reference. When we pass the addresses to
function, the parameters receiving the addresses should be pointers. So
change of formal parameters in the function will affect actual parameters in
the calling function.
Example :
#include<stdio.h>
void swap(int *a,int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
}
void main()
{
void swap(int*,int*);
int a=10,b=20;
printf("Values before swapping : ");
printf("\na=%d",a);
printf("\nb=%d",b);
swap(&a,&b); // call by reference
printf("\nValues after swapping : ");
Page 10
C Programming Unit – V
printf("\na=%d",a);
printf("\nb=%d",b);
}
Output:
Values before swapping :
a=10
b=20
Values after swapping :
a=20
b=10
Call by Value Call by Reference
When function is called then When function is called then
values of variables are passed. addresses of variables are
passed.
formal parameters contains the formal parameters contains the
values of actual arguments. addresses of actual arguments.
modifications done to formal modifications done to formal
parameters does not affect actual parameters directly affect actual
arguments. arguments.
Dynamic Memory Allocation Techniques (or)
Dynamic Memory Management Functions
The process of allocating memory dynamically i.e., during runtime of the
program is known as dynamic memory allocation. The standard C library has the
four built in functions known as dynamic memory management functions which
help in dealing with the dynamic memory allocation. These functions are given
below.
Function Task
malloc( ) Allocates requested size of bytes and returns a pointer to the
first byte of the allocated space
calloc( ) Allocates space for an array of elements, initializes them to
zero and then returns a pointer to the memory
realloc( ) Modifies the size of previously allocated space
free( ) Frees previously allocated space
The declarations for the functions are available in the header file stdlib.h
malloc( ):
the malloc( ) stands for memory allocation. It allocates a single block of
memory of requested size and returns a pointer to the first byte of the block. The
general form is
Page 11
C Programming Unit – V
Syntax :
ptr = (datatype *) malloc(bytesize);
where bytesize is the number of bytes to be allocated and ptr is a pointer of
type datatype, which collects the address of the first byte of memory block
allocated. The memory block allocated will have garbage values. If there is not
enough space, a NULL pointer is returned.
Ex:
Consider the statements
int *p;
p = (int *) malloc( 50));
on successful execution of this statement, a memory space 50 bytes is
reserved and the address of the first byte of the memory allocated is
assigned to the pointer “p” of type of int.
calloc( ): The calloc( ) stands for contiguous memory allocation. It allocates
multiple blocks of memory, all of which are of the same size and returns a
pointer to the first byte of the first block. The general form is
Syntax :
ptr = (data type *) calloc( no of blocks , block size);
Page 12
C Programming Unit – V
where n is the number of blocks of memory to be allocated and blocksize is
the number of bytes in each block and ptr is a pointer of type datatype,
which collects the address of the first byte of the first memory block
allocated. The memory block allocated will be filled with zeros. If there is not
enough space, a NULL pointer is returned.
#include<stdio.h>
#include<stdlib.h>
void main()
{
int *a,n,i;
printf("Enter array size : ");
scanf("%d",&n);
a=(int *)calloc( n,4 );
printf("Enter %d elements : ",n);
for( i=0;i<n;i++ )
scanf("%d",a+i);
printf("Array is : ");
for( i=0;i<n;i++ )
printf("%5d",*(a+i));
}
Output:
Enter array size : 6
Enter 6 elements : 10 50 20 40 70 30
Array is : 10 50 20 40 70 30
realloc( ):
realloc stands for memory re allocation. Sometimes we may need to change
the size of the memory block allocated by either malloc( ) or calloc( ) ,
during runtime itself. This can be accomplished by realloc( ).
The general form is
newptr = (datatype *) realloc( oldptr, newsize);
Page 13
C Programming Unit – V
where oldptr points to block of memory previously allocated by malloc( ) or
calloc( ), newptr is the size of the block to be reallocated.
On successful execution, the function returns a pointer to the first byte
of reallocated memory block. If the function is unsuccessful in locating
additional space, it returns a NULL pointer and the original block is freed.
#include<stdio.h>
#include<stdlib.h>
void main()
{
char *city;
city=(char *)malloc(10);
strcpy(city,”Hyderabad”);
printf(“City=%s”,city);
city=(char *)realloc(city,14);
strcpy(city,”Vishakapatnum”);
printf(“City=%s”,city);
}
output:
City=Hyderabad
City=Vishakapatnam
free( ):
The free( ) is to release a block of memory which is previously allocated so that it
can be reused for some other purpose. The general form is
free(ptr);
where ptr is a pointer, which points to the first byte of the memory block to be
released.
#include<stdio.h>
#include<stdlib.h>
void main()
{
int *a,n,i;
printf("Enter array size : ");
scanf("%d",&n);
a=(int*)malloc( n*4 );
printf("Enter %d elements : ",n);
for( i=0;i<n;i++ )
scanf("%d",a+i);
Page 14
C Programming Unit – V
printf("Array is : ");
for( i=0;i<n;i++ )
printf("%5d",*(a+i));
free(a);
}
Advantages of Pointers
1. Effective Memory Management :
Pointers allow dynamic memory allocation using malloc(), calloc(), etc. This
helps to allocate memory at runtime and free it when no longer needed.
2. Improve the performance :
Pointers allow direct access to [Link] using pointers (e.g.,
passing by reference) avoid copying large data, improving speed.
3. Function arguments passed by reference :
Pointers allow passing function arguments by reference, so changes
inside the function affect the original variable.
4. Effective array and string handling :
Pointers are widely used to traverse arrays and strings effectively.
5. Helps in handling complex data structures :
pointers Helps in handling complex data structures like linked list, stack,
queues, trees, graphs etc.
6. Return more values from function:
Pointers provide a way to return more than one value from functions.
7. Multiple Variable Access Using Single Pointer :
A single pointer can be reused to access multiple variables (e.g., arrays or
loops).
8. Space complexity:
Reduces the storage space and complexity of the program
Disadvantages of Pointers
1. Complex and Error-Prone
Pointers can be confusing, especially for beginners. Improper use can lead to
bugs that are hard to find and fix.
2. Risk of Memory Leaks
If dynamically allocated memory is not freed using free(), it causes a memory
leak. Over time, this can exhaust system memory.
Page 15
C Programming Unit – V
3. Dangling Pointers
A pointer pointing to a memory location that has been deleted (freed) is called
a dangling pointer. Accessing it can lead to unpredictable behavior or
crashes.
4. Pointer Arithmetic Can Be Dangerous
Operations like ptr++, ptr--, *(ptr+1) can access invalid memory if not used
correctly.
5. Security Risks
Improper pointer use can be buffer overflows.
6. Null Pointer Dereferencing
Using a pointer that hasn’t been initialized (i.e., NULL or garbage value) can
cause program crashes.
7. Increased Debugging Time
Pointer-related bugs are difficult to trace and debug.
8. Hard to Maintain
Programs that use lots of pointers are harder to read, understand, and
maintain.
Command line arguments
Command Line Arguments allow the user to pass values (arguments) to a
program when it is executed from the command line (like terminal or
command prompt).
They help make a program more dynamic and user-controlled at runtime.
Main Function with Arguments:
int main(int argc, char *argv[])
Parameter Meaning
Number of command line arguments
argc (Argument Count)
(including program name)
Array of strings (character pointers)
argv[] (Argument Vector)
holding all arguments
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Total arguments: %d\n", argc);
for (int i = 0; i < argc; i++)
{
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
Page 16
C Programming Unit – V
}
Important Points:
argv[0] is always the program name.
Arguments are passed as strings (char *), even if you pass numbers.
You need to convert strings to numbers using atoi(), atof(), etc., if needed.
Page 17