C Pointers - Module III
C Pointers - Module III
Mrs.A.Reshma Parveen
C Pointers
• The pointer in C language is a variable which stores the address of another variable.
• This variable can be of type int, char, array, function, or any other pointer.
• The size of the pointer depends on the architecture. However, in 32-bit architecture the size of a
pointer is 2 byte.
• Consider the following example to define a pointer which stores the address of an integer.
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
Mrs.A.Reshma Parveen
C Pointers
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection
pointer used to dereference a pointer.
Pointer Example
Mrs.A.Reshma Parveen
C Pointers
• As you can see in the above figure, pointer variable stores the address of number variable, i.e., fff4. The
value of number variable is 50. But the address of pointer variable p is aaa3.
• By the help of * (indirection operator), we can print the value of pointer variable p.
• Let's see the pointer example as explained for the above figure.
#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the number therefore printing p gives the address of
number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a pointer therefore if we print *p, we
will get the value stored at the address contained by p.
return 0;
}
Mrs.A.Reshma Parveen
C Pointers
Advantage of pointer
• 1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees, etc. and
used with arrays, structures, and functions.
• 2) We can return multiple values from a function using the pointer.
• 3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
• There are many applications of pointers in c language.
1) Dynamic memory allocation
In c language, we can dynamically allocate memory using malloc() and calloc() functions where the pointer is
used.
2) Arrays, Functions, and Structures
Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and improves
the performance
Mrs.A.Reshma Parveen
C Pointers Operators
Address Of (&) Operator
The address of operator '&' returns the address of a variable. But, we need to use %u to display the address
of a variable.
#include<stdio.h>
int main(){
int number=50;
return 0;
Mrs.A.Reshma Parveen
C Pointers Operators
NULL Pointer
• A pointer that is not assigned any value but NULL is known as the NULL pointer.
• If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL
value.
• It will provide a better approach.
Example:
#include <stdio.h>
int main () {
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}
Mrs.A.Reshma Parveen
C Pointers
Pointer Program to swap two numbers without using the 3rd variable.
#include<stdio.h>
int main()
{
int a=10,b=20,*p1=&a,*p2=&b;
printf("Before swap: *p1=%d *p2=%d",*p1,*p2);
*p1=*p1+*p2;
*p2=*p1-*p2;
*p1=*p1-*p2;
printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);
return 0;
}
Mrs.A.Reshma Parveen
C Pointers
Reading complex pointers
There are several things which must be taken into the consideration while reading the complex pointers in C. Lets see the
precedence and associativity of the operators which are used regarding pointers.
Mrs.A.Reshma Parveen
C Pointer Arithmetic
• We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as we
know that pointer contains the address, the result of an arithmetic operation performed on the pointer
will also be a pointer if the other operand is of type integer. In pointer-from-pointer subtraction, the
result will be an integer value. Following arithmetic operations are possible on the pointer in C language:
• Increment
• Decrement
• Addition
• Subtraction
• Comparison
Mrs.A.Reshma Parveen
C Pointer Arithmetic
Incrementing Pointer in C
• If we increment a pointer by 1, the pointer will start pointing to the immediate next location. This is
somewhat different from the general arithmetic since the value of the pointer will get increased by the size
of the data type to which the pointer is pointing.
• We can traverse an array by using the increment operation on a pointer which will keep pointing to every
element of the array, perform some operation on that, and update itself in a loop.
new_address= current_address + +
Mrs.A.Reshma Parveen
C Pointer Arithmetic
#include<stdio.h>
int main(){
int number=50;
p=p++;
printf("After increment: Address of p variable is %u \n",p); // in our case, p will get incremented by 4 bytes.
return 0;
Mrs.A.Reshma Parveen
C Pointer Arithmetic
Traversing an array by using pointer
#include<stdio.h>
void main ()
{
int arr[5] = {1, 2, 3, 4, 5};
int *p = arr;
int i;
printf("printing array elements...\n");
for(i = 0; i< 5; i++)
{
printf("%d ",*(p++));
}
}
Mrs.A.Reshma Parveen
C Pointer Arithmetic
Decrementing Pointer in C
#include <stdio.h>
void main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p--;
printf("After decrement: Address of p variable is %u \n",p);
// P will now point to the immidiate previous location.
}
Mrs.A.Reshma Parveen
C Pointer Arithmetic new_address= current_address + i * size_of(data type)
C Pointer Addition
#include<stdio.h>
int main(){
int number=50;
return 0; }
Mrs.A.Reshma Parveen
C Pointer Arithmetic
C Pointer Subtraction
#include<stdio.h>
int main(){
int number=50;
return 0; }
Mrs.A.Reshma Parveen
C Pointer Arithmetic
Subtraction of Two Pointers
• The subtraction of two pointers is possible only when they have the same data type. The result is
generated by calculating the difference between the addresses of the two pointers and calculating how
many bits of data it is according to the pointer data type. The subtraction of two pointers gives the
increments between the two pointers.
• For Example:
Two integer pointers say ptr1(address:1000) and ptr2(address:1016) are subtracted. The difference
between address is 16 bytes. Since the size of int is 2 bytes, therefore the increment between ptr1 and
ptr2 is given by (16/2) = 8.
Mrs.A.Reshma Parveen
C Pointer Arithmetic
#include <stdio.h>
int main()
{
int x;
int N = 4;
// Incrementing ptr2 by 3
ptr2 = ptr2 + 3;
return 0;
}
Mrs.A.Reshma Parveen
C Pointer Arithmetic
Comparison of pointers of the same type:
• We can compare the two pointers by using the comparison operators in C. We can implement this by using
all operators in C >, >=, <, <=, ==, !=. It returns true for the valid condition and returns false for the
unsatisfied condition.
• Step 1 : Initialize the integer values and point these integer values to the pointer.
• Step 2 : Now, check the condition by using comparison or relational operators on pointer variables.
Mrs.A.Reshma Parveen
C Pointer Arithmetic
if(*p3==*p1)
#include <stdio.h>
{
int main() { printf("\nBoth the values are equal");
int num1=5,num2=6,num3=5; }
if(*p3!=*p2)
int *p1=&num1 {
int *p2=&num2; printf("\nBoth the values are not equal");
}
int *p3=&num3;
if(*p1<*p2)
return 0;
{ }
printf("\n%d less than %d",*p1,*p2);
}
if(*p2>*p1)
{
printf("\n%d greater than %d",*p2,*p1);
}
Mrs.A.Reshma Parveen
Array of Pointers
Before we understand the concept of arrays of pointers, let us consider the following example,
which uses an array of 3 integers
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i;
for (i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, var[i] );
}
return 0;
}
Mrs.A.Reshma Parveen
Array of Pointers
Following is the declaration of an array of pointers to an integer.It declares ptr as an array of MAX integer pointers. Thus, each element in ptr,
holds a pointer to an int value.
int *ptr[MAX];
The following example uses three integers, which are stored in an array of pointers, as follows
#include <stdio.h>
const int MAX = 3;
void main () {
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++)
{
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
}
Mrs.A.Reshma Parveen
Array of Pointers
You can also use an array of pointers to character to store a list of strings as follows −
#include <stdio.h>
void main () {
int i = 0;
}
Mrs.A.Reshma Parveen
Array of Pointers
*names[ ] is an array whose elements are pointers to the base address of string.
names[0] is pointer to base address of string Zara, names[1] for Hina, names[2] for Nuha and so on
1005 1010 1015
1000
Z a r a \0 H i n a \0 N u h a \0 S a r a \0
1000
names[0]
1005
names[1]
1010
names[2]
1015
names[3]
Mrs.A.Reshma Parveen
Arrays and Pointers
Relationship Between Arrays and Pointers
• An array is a block of sequential data. Let's write a program to print addresses of array elements.
#include <stdio.h>
int main() {
int x[4];
int i;
return 0;
}
Mrs.A.Reshma Parveen
Arrays and Pointers
Relationship Between Arrays and Pointers
• There is a difference of 4 bytes between two consecutive elements of array x. It is because the size of int is
4 bytes (on our compiler).
• Notice that, the address of &x[0] and x is the same. It's because the variable name x points to the first
element of the array.
• From the above example, it is clear that &x[0] is equivalent to x. And, x[0] is equivalent to *x.
Similarly,
Mrs.A.Reshma Parveen
Arrays and Pointers
Example 1: Pointers and Arrays
#include <stdio.h>
int main() {
int i, x[6], sum = 0;
printf("Enter 6 numbers: ");
for(i = 0; i < 6; ++i) {
// Equivalent to scanf("%d", &x[i]);
scanf("%d", x+i);
// Equivalent to sum += x[i]
sum += *(x+i);
}
printf("Sum = %d", sum);
return 0;
}
Mrs.A.Reshma Parveen
Arrays and Pointers
Example 2: Arrays and Pointers
#include <stdio.h>
int main() {
int x[5] = {1, 2, 3, 4, 5};
int* ptr;
// ptr is assigned the address of the third element
ptr = &x[2];
printf("*ptr = %d \n", *ptr); // 3
printf("*(ptr+1) = %d \n", *(ptr+1)); // 4
In this example, &x[2], the address of the third element, is
printf("*(ptr-1) = %d", *(ptr-1)); // 2
assigned to the ptr pointer. Hence, 3 was displayed when we
printed *ptr.
return 0;
And, printing *(ptr+1) gives us the fourth element. Similarly,
} printing *(ptr-1) gives us the second element.
Mrs.A.Reshma Parveen
Pointer to Pointer
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer
contains the address of a variable. When we define a pointer to a pointer, the first pointer contains
the address of the second pointer, which points to the location that contains the actual value as
shown below.
A variable that is a pointer to a pointer must be declared as such. This is done by placing an
additional asterisk in front of its name. For example, the following declaration declares a pointer to
a pointer of type int −
int **var;
Mrs.A.Reshma Parveen
Pointer to Pointer
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
int **p2;//pointer to pointer
p=&number;//stores the address of number variable
p2=&p;
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p);
printf("Value of *p variable is %d \n",*p);
printf("Address of p2 variable is %x \n",p2);
printf("Value of **p2 variable is %d \n",**p2);
return 0;
}
Mrs.A.Reshma Parveen
Pointer to Pointer
#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;
}
Mrs.A.Reshma Parveen
Pointer to Pointer
#include<stdio.h>
void main ()
{
int a[10] = {100, 206, 300, 409, 509, 601}; //Line 1
int *p[] = {a, a+1, a+2, a+3, a+4, a+5}; //Line 2
int **pp = p; //Line 3
pp++; // Line 4
printf("%d %d %d\n",pp-p,*pp - a,**pp); // Line 5
*pp++; // Line 6
printf("%d %d %d\n",pp-p,*pp - a,**pp); // Line 7
++*pp; // Line 8
printf("%d %d %d\n",pp-p,*pp - a,**pp); // Line 9
++**pp; // Line 10
printf("%d %d %d\n",pp-p,*pp - a,**pp); // Line 11
}
Mrs.A.Reshma Parveen
Pointer to Pointer
Explanation
Mrs.A.Reshma Parveen
Pointer
Explanation
to Pointer
Mrs.A.Reshma Parveen
Pointer
Explanation
to Pointer
Mrs.A.Reshma Parveen
Pointer
Explanation
to Pointer
Mrs.A.Reshma Parveen
Pointer
Explanation
to Pointer
Mrs.A.Reshma Parveen
Assignment
1.Write a C program to create, initialize and use pointers
Mrs.A.Reshma Parveen
Void Pointer
Till now, we have studied that the address assigned to a pointer should be of the same type as specified in
the pointer declaration. For example, if we declare the int pointer, then this int pointer cannot point to the
float variable or some other type of variable, i.e., it can point to only int type variable. To overcome this
problem, we use a pointer to void. A pointer to void means a generic pointer that can point to any data
type. We can assign the address of any data type to the void pointer, and a void pointer can be assigned to
any type of the pointer without performing any explicit typecasting.
Syntax of void pointer
void *pointer name;
Declaration of the void pointer is given below:
void *ptr;
In the above declaration, the void is the type of the pointer, and 'ptr' is the name of the pointer.
Mrs.A.Reshma Parveen
Void Pointer
Let us consider some examples:
int i=9; // integer variable initialization.
float f=10.5;
int *p; // integer pointer declaration.
float *fp; // floating pointer declaration.
void *ptr; // void pointer declaration.
P=&f; //incorrect
fp=&i; // incorrect
ptr=&f; // correct
ptr=&i; // correct
Mrs.A.Reshma Parveen
Void Pointer
•Dereferencing a void pointer in C
The void pointer in C cannot be dereferenced directly. Let's see the below example.
#include <stdio.h>
int main()
{
int a=90;
void *ptr;
ptr=&a;
printf("Value which is pointed by ptr pointer : %d",*ptr);
return 0;
}
In the above code, *ptr is a void pointer which is pointing to the integer variable 'a'. As we already know
that the void pointer cannot be dereferenced, so the above code will give the compile-time error because
we are printing the value of the variable pointed by the pointer 'ptr' directly.
Mrs.A.Reshma Parveen
Void Pointer
Now, we rewrite the above code to remove the error.
#include <stdio.h>
void main()
{
int a=90;
void *ptr;
ptr=&a;
printf("Value which is pointed by ptr pointer : %d",*(int*)ptr);
}
In the above code, we typecast the void pointer to the integer pointer by using the statement given below:
(int*)ptr;
Then, we print the value of the variable which is pointed by the void pointer 'ptr' by using the statement
given below:
*(int*)ptr;
Mrs.A.Reshma Parveen
Void Pointer
We use void pointers because of its reusability. Void pointers can store the object of any type, and we can retrieve the
object of any type by using the indirection operator with proper typecasting.
Let's understand through an example.
#include<stdio.h>
int main()
{
int a=56; // initialization of a integer variable 'a'.
float b=4.5; // initialization of a float variable 'b'.
char c='k'; // initialization of a char variable 'c'.
void *ptr; // declaration of void pointer.
// assigning the address of variable 'a'.
ptr=&a;
printf("value of 'a' is : %d",*((int*)ptr));
// assigning the address of variable 'b'.
ptr=&b;
printf("\nvalue of 'b' is : %f",*((float*)ptr));
// assigning the address of variable 'c'.
ptr=&c;
printf("\nvalue of 'c' is : %c",*((char*)ptr));
return 0;
}
Mrs.A.Reshma Parveen
C Function Pointer
As we know that we can create a pointer of any data type such as int, char, float, we can also create a
pointer pointing to a function. The code of a function always resides in memory, which means that the
function has some address. We can get the address of memory by using the function pointer.
Let's see a simple example.
#include <stdio.h>
int main()
{
printf("Address of main() function is %p",main);
return 0;
}
The above code prints the address of main() function.
In the above output, we observe that the main() function has some address. Therefore, we conclude that
every function has some address.
Mrs.A.Reshma Parveen
C Function Pointer
Declaration of a function pointer
Till now, we have seen that the functions have addresses, so we can create pointers that can contain
these addresses, and hence can point them.
Syntax of function pointer
return type (*ptr_name)(type1, type2…);
For example:
int (*ip) (int);
In the above declaration, *ip is a pointer that points to a function which returns an int value and accepts
an integer value as an argument.
float (*fp) (float);
In the above declaration, *fp is a pointer that points to a function that returns a float value and accepts a
float value as an argument.
Mrs.A.Reshma Parveen
C Function Pointer
We can observe that the declaration of a function is similar to the declaration of a function pointer except that
the pointer is preceded by a '*'. So, in the above declaration, fp is declared as a function rather than a pointer.
Till now, we have learnt how to declare the function pointer. Our next step is to assign the address of a
function to the function pointer.
float (*fp) (int , int); // Declaration of a function pointer.
float func( int , int ); // Declaration of function.
fp = func; // Assigning address of func to the fp pointer.
In the above declaration, 'fp' pointer contains the address of the 'func' function.
Note: Declaration of a function is necessary before assigning the address of a function to the function
pointer.
Mrs.A.Reshma Parveen
C Function Pointer
Calling a function through a function pointer
We already know how to call a function in the usual way. Now, we will see how to call a function using a
function pointer.
Suppose we declare a function as given below:
float func(int , int); // Declaration of a function.
Calling an above function using a usual way is given below:
result = func(a , b); // Calling a function using usual ways.
Calling a function using a function pointer is given below:
result = (*fp)( a , b); // Calling a function using function pointer.
Or
result = fp(a , b); // Calling a function using function pointer, and indirection operator can be removed
The effect of calling a function by its name or function pointer is the same. If we are using the function pointer,
we can omit the indirection operator as we did in the second case. Still, we use the indirection operator as it
makes it clear to the user that we are using a function pointer.
Mrs.A.Reshma Parveen
C Function Pointer
Let's consider an example:
float (*add)(); // this is a legal declaration for the function pointer
float *add(); // this is an illegal declaration for the function pointer
A function pointer can also point to another function, or we can say that it holds the address of another function.
float add (int a, int b); // function declaration
float (*a)(int, int); // declaration of a pointer to a function
a=add; // assigning address of add() to 'a' pointer
In the above case, we have declared a function named as 'add'. We have also declared the function pointer (*a) which
returns the floating-type value, and contains two parameters of integer type. Now, we can assign the address
of add() function to the 'a' pointer as both are having the same return type(float), and the same type of arguments.Now,
'a' is a pointer pointing to the add() function. We can call the add() function by using the pointer, i.e., 'a'. Let's see how we
can do that:
a(2, 3);
The above statement calls the add() function by using pointer 'a', and two parameters are passed in 'a', i.e., 2 and 3.
Mrs.A.Reshma Parveen
C Function Pointer
Let's understand the function pointer through an example.
#include <stdio.h>
int add(int,int);
void main()
{
int a,b;
int (*ip)(int,int);
int result;
printf("Enter the values of a and b : ");
scanf("%d %d",&a,&b);
ip=add;
result=(*ip)(a,b);
printf("Value after addition is : %d",result);
}
int add(int a,int b)
{
int c=a+b;
return c;
}
Mrs.A.Reshma Parveen
C Function Pointer
Function pointer as argument in C
Till now, we have seen that in C programming, we can pass the variables as an argument to a function.
We cannot pass the function as an argument to another function. But we can pass the reference of a
function as a parameter by using a function pointer. This process is known as call by reference as the
function parameter is passed as a pointer that holds the address of arguments. If any change made by
the function using pointers, then it will also reflect the changes at the address of the passed variable.
Therefore, C programming allows you to create a pointer pointing to the function, which can be further
passed as an argument to the function. We can create a function pointer as follows:
(type) (*pointer_name)(parameter);
In the above syntax, the type is the variable type which is returned by the function, *pointer_name is
the function pointer, and the parameter is the list of the argument passed to the function.
Mrs.A.Reshma Parveen
C Function Pointer
Let's see a simple example of how we can pass the function pointer as a parameter.
void display(void (*p)(int))
{
for(int i=1;i<=5;i++)
{
p(i);
}
}
void print_numbers(int num)
{
printf(num);
}
int main()
{
void (*p)(int); // void function pointer declaration
printf("The values are :");
display(print_numbers);
return 0;
}
Mrs.A.Reshma Parveen
C Function Pointer
In the above code,
•We have defined two functions named 'display()' and print_numbers().
•Inside the main() method, we have declared a function pointer named as (*p), and we call the display()
function in which we pass the print_numbers() function.
•When the control goes to the display() function, then pointer *p contains the address of print_numbers()
function. It means that we can call the print_numbers() function using function pointer *p.
•In the definition of display() function, we have defined a 'for' loop, and inside the for loop, we call the
print_numbers() function using statement p(i). Here, p(i) means that print_numbers() function will be called
on each iteration of i, and the value of 'i' gets printed.
Mrs.A.Reshma Parveen
C Function Pointer
Passing a function's address as an argument to other function:
include <stdio.h>
void func1(void (*ptr)());
void func2();
int main()
{
func1(func2);
return 0;
}
void func1(void (*ptr)())
{
printf("Function1 is called");
(*ptr)(); In this code, we have created two functions, i.e., func1() and func2().
} The func1() function contains the function pointer as an argument.
void func2() In the main() method, the func1() method is called in which we pass
{ the address of func2. When func1() function is called, 'ptr' contains
printf("\nFunction2 is called"); the address of 'func2'. Inside the func1() function, we call the
func2() function by dereferencing the pointer 'ptr' as it contains the
}
address of func2.
Mrs.A.Reshma Parveen
C Function Pointer
Function pointers are used in those applications where we do not know in advance which function will be
called. In an array of function pointers, array takes the addresses of different functions, and the appropriate
Mrs.A.Reshma Parveen
C Function Pointer
#include <stdio.h> float add(float x,float y)
float add(float,float); {
float sub(float,float); float a=x+y;
float mul(float,float); return a;
float div(float,float); }
void main() float sub(float x,float y)
{ {
float x; // variable declaration. float a=x-y;
float y; return a;
float (*fp[4]) (float,float); // function pointer declaration. }
fp[0]=add; float mul(float x,float y)
fp[1]=sub; {
fp[2]=mul; float a=x*y;
fp[3]=div; return a;
printf("Enter the values of x and y :"); }
scanf("%f %f",&x,&y); float div(float x,float y)
float r=(*fp[0]) (x,y); // Calling add() function. {
printf("\nSum of two values is : %f",r); float a=x/y;
r=(*fp[1]) (x,y); // Calling sub() function. return a;
printf("\nDifference of two values is : %f",r); }
r=(*fp[2]) (x,y); // Calliung sub() function.
printf("\nMultiplication of two values is : %f",r);
r=(*fp[3]) (x,y); // Calling div() function.
printf("\nDivision of two values is : %f",r);
}
Mrs.A.Reshma Parveen
C Function Pointer
In the above code, we have created an array of function pointers that contain the addresses of four
functions. After storing the addresses of functions in an array of function pointers, we call the functions
Mrs.A.Reshma Parveen
Assignment
• Create a calculator using C with the help of array of function pointer.
Menu
**********************
0.Addition
1.Subtraction
2.Multiplication
3.Division
Mrs.A.Reshma Parveen