0% found this document useful (0 votes)
19 views16 pages

Chapter 8

Uploaded by

mjenish99
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views16 pages

Chapter 8

Uploaded by

mjenish99
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Pointer

Introduction
A Pointer in C language is a variable which holds the address of another variable of same data
type.
Pointers are used to access memory and manipulate the address.
Pointers are one of the most distinct and exciting features of C language. It provides power and
flexibility to the language. Although pointers may appear a little confusing and complicated in
the beginning, but trust me, once you understand the concept, you will be able to do so much
more with C language.
Before we start understanding what pointers are and what they can do, let's start by
understanding what does "Address of a memory location" means?
Address in C : Whenever a variable is defined in C language, a memory location is assigned for
it, in which it's value will be stored. We can easily check this memory address, using
the & symbol.
If var is the name of the variable, then &var will give it's address.
Let's write a small program to see memory address of any variable that we define in our
program.
#include<stdio.h>
void main()
{
int var = 7;
printf("Value of the variable var is: %d\n", var);
printf("Memory address of the variable var is: %x\n", &var);
}
Value of the variable var is: 7
Memory address of the variable var is: bcc7a00
You must have also seen in the function scanf(), we mention &var to take user input for any
variable var.
scanf("%d", &var);
This is used to store the user inputted value to the address of the variable var.
Concept of Pointers : Whenever a variable is declared in a program, system allocates a location
i.e an address to that variable in the memory, to hold the assigned value. This location has its
own address number, which we just saw above. Let us assume that system has allocated memory
location 80F for a variable a.
int a = 10;

Compiled By : Deepak Kr. Singh, Pradip Khanal


We can access the value 10 either by using the variable name a or by using its address 80F.
The question is how we can access a variable using it's address? Since the memory addresses are
also just numbers, they can also be assigned to some other variable. The variables which are used
to hold memory addresses are called Pointer variables.
A pointer variable is therefore nothing but a variable which holds an address of some other
variable. And the value of a pointer variable gets stored in another memory location.

Benefits of using pointers


Below we have listed a few benefits of using pointers:

 Pointers are more efficient in handling Arrays and Structures.


 Pointers allow references to function and thereby helps in passing of function as
arguments to other functions.
 It reduces length of the program and its execution time as well.
 It allows C language to support Dynamic Memory management.

Declaration of Pointer variable


General syntax of pointer declaration is,
datatype *pointer_name;
Data type of a pointer must be same as the data type of the variable to which the pointer variable
is pointing. void type pointer works with all data types, but is not often used.
Here are a few examples:
int *ip // pointer to integer variable
float *fp; // pointer to float variable
double *dp; // pointer to double variable
char *cp; // pointer to char variable
Initialization of Pointer variable
Pointer Initialization is the process of assigning address of a variable to a pointer variable.
Pointer variable can only contain address of a variable of the same data type. In C
language address operator & is used to determine the address of a variable.

Compiled By : Deepak Kr. Singh, Pradip Khanal


The & (immediately preceding a variable name) returns the address of the variable associated
with it.
#include<stdio.h>
void main()
{
int a = 10;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization
}
Pointer variablea always point to variables of same datatype. Let's have an example to showcase
this:
#include<stdio.h>
void main()
{
float a;
int *ptr;
ptr = &a; // ERROR, type mismatch
}

If you are not sure about which variable's address to assign to a pointer variable while
declaration, it is recommended to assign a NULL value to your pointer variable. A pointer which
is assigned a NULL value is called a NULL pointer.
#include <stdio.h>
int main()
{
int *ptr = NULL;
return 0;
}
Using the pointer or Dereferencing of Pointer
Once a pointer has been assigned the address of a variable, to access the value of the variable,
pointer is dereferenced, using the indirection operator or dereferencing operator *.
#include <stdio.h>
int main()
{
int a, *p; // declaring the variable and pointer
a = 10;
p = &a; // initializing the pointer
printf("%d", *p); //this will print the value of 'a'
printf("%d", *&a); //this will also print the value of 'a'
printf("%u", &a); //this will print the address of 'a'
printf("%u", p); //this will also print the address of 'a'
printf("%u", &p); //this will print the address of 'p'
return 0;
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


Points to remember while using pointers:
 While declaring/initializing the pointer variable, * indicates that the variable is a pointer.
 The address of any variable is given by preceding the variable name with Ampersand &.
 The pointer variable stores the address of a variable. The declaration int *a doesn't mean
that a is going to contain an integer value. It means that a is going to contain the address
of a variable storing integer value.
 To access the value of a certain address stored by a pointer variable, * is used. Here,
the * can be read as 'value at'.
Time for an Example
#include <stdio.h>
int main()
{
int i = 10; // normal integer variable storing value 10
int *a; // since '*' is used, hence its a pointer variable
/*
'&' returns the address of the variable 'i'
which is stored in the pointer variable 'a'
*/
a = &i;
/*
below, address of variable 'i', which is stored
by a pointer variable 'a' is displayed
*/
printf("Address of variable i is %u\n", a);
/*
below, '*a' is read as 'value at a'
which is 10
*/
printf("Value at the address, which is stored by pointer variable a is %d\n", *a);
return 0;
}
Address of variable i is 2686728 (The address may vary)
Value at an address, which is stored by pointer variable a is 10

Compiled By : Deepak Kr. Singh, Pradip Khanal


Pointer to a Pointer(Double Pointer)
Pointers are used to store the address of other variables of similar data type. But if you want to
store the address of a pointer variable, then you again need a pointer to store it. Thus, when one
pointer variable stores the address of another pointer variable, it is known as Pointer to
Pointer variable or Double Pointer.
Syntax:
int **p1;
Here, we have used two indirection operator(*) which stores and points to the address of a
pointer variable i.e, int *. If we want to store the address of this (double pointer) variable p1, then
the syntax would become:
int ***p2
Simple program to represent Pointer to a Pointer
#include <stdio.h>
int main() {
int a = 10;
int *p1; //this can store the address of variable a
int **p2;
/*
this can store the address of pointer variable p1 only.
It cannot store the address of variable 'a'
*/
p1 = &a;
p2 = &p1;
printf("Address of a = %u\n", &a);
printf("Address of p1 = %u\n", &p1);
printf("Address of p2 = %u\n\n", &p2);
// below print statement will give the address of 'a'
printf("Value at the address stored by p2 = %u\n", *p2);
printf("Value at the address stored by p1 = %d\n\n", *p1);
printf("Value of **p2 = %d\n", **p2); //read this *(*p2)
/*
This is not allowed, it will give a compile time error-
p2 = &a;
printf("%u", p2);
*/
return 0;
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


Address of a = 2686724
Address of p1 = 2686728
Address of p2 = 2686732
Value at the address stored by p2 = 2686724
Value at the address stored by p1 = 10
Value of **p2 = 10

Explanation of the above program

 p1 pointer variable can only hold the address of the variable a (i.e Number of indirection
operator(*)-1 variable). Similarly, p2 variable can only hold the address of variable p1. It
cannot hold the address of variable a.
 p2 gives us the value at an address stored by the p2 pointer. p2 stores the address
of p1pointer and value at the address of p1is the address of variable a. Thus, *p2 prints
address of a.
 **p2 can be read as *(*p2). Hence, it gives us the value stored at the address *p2. From
above statement, you know *p2 means the address of variable a. Hence, the value at the
address *p2 is 10. Thus, **p2 prints 10.

Compiled By : Deepak Kr. Singh, Pradip Khanal


Pointer and Arrays
When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address i.e address of the first element of the array is also allocated
by the compiler.
Suppose we declare an array arr,
int arr[5] = { 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two bytes, the five
elements will be stored as follows:

Here variable arr will give the base address, which is a constant pointer pointing to the first
element of the array, arr[0]. Hence arr contains the address of arr[0] i.e 1000. In short, arr has
two purpose - it is the name of the array and it acts as a pointer pointing towards the first element
in the array.
arr is equal to &arr[0] by default
We can also 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 the array arr using p++ to move from one element to
another.
NOTE: You cannot decrement a pointer once incremented. p-- won't work.
Pointer to Array
As studied above, we can use a pointer to point to an array, and then we can use that pointer to
access the array elements. Lets have an example,
#include <stdio.h>
int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
return 0;
}

Compiled By : Deepak Kr. Singh, Pradip Khanal


In the above program, the pointer *p will print all the values stored in the array one by one. We
can also use the Base address (a in above case) to act as a pointer and print all the values.

The generalized form for using pointer with an array,


*(a+i)
is same as:
a[i]

Pointer to Multidimensional Array


A multidimensional array is of form, a[i][j]. Lets see how we can make a pointer point to such an
array. As we know now, name of the array gives its base address. In a[i][j], a will give the base
address of this array, even a + 0 + 0 will also give the base address, that is the address
of a[0][0]element.
Here is the generalized form for using pointer with multidimensional arrays.
*(*(a + i) + j)
which is same as,
a[i][j]

Pointer and Character strings


Pointer can also be used to create strings. Pointer variables of char type are treated as string.
char *str = "Hello";
The above code creates a string and stores its address in the pointer variable str. The
pointer strnow points to the first character of the string "Hello". Another important thing to note
here is that the string created using char pointer can be assigned a value at runtime.
char *str;
str = "hello"; //this is 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 *.

Compiled By : Deepak Kr. Singh, Pradip Khanal


Array of Pointers
We can also have array of pointers. Pointers are very helpful in handling character array with
rows of varying length.
char *name[3] = {
"Adam",
"chris",
"Deniel"
};
//Now lets see same array without using pointer
char name[3][20] = {
"Adam",
"chris",
"Deniel"
};

In the second approach memory wastage is more, hence it is prefered to use pointer in such
cases.
When we say memory wastage, it doesn't means that the strings will start occupying less space,
no, characters will take the same space, but when we define array of characters, a contiguos
memory space is located equal to the maximum size of the array, which is a wastage, which can
be avoided if we use pointers instead.

Pointer to Structure Array


Like we have array of integers, array of pointers etc, we can also have array of structure
variables. And to use the array of structure variables efficiently, we use pointers of structure
type. We can also have pointer to a single structure variable, but it is mostly used when we are
dealing with array of structure variables.
#include <stdio.h>
struct Book
{
char name[10];
int price;
};

Compiled By : Deepak Kr. Singh, Pradip Khanal


int main()
{
struct Book a; //Single structure variable
struct Book* ptr; //Pointer of Structure type
ptr = &a;
struct Book b[10]; //Array of structure variables
struct Book* p; //Pointer of Structure type
p = &b;
return 0;
}

Accessing Structure Members with Pointer


To access members of structure using the structure variable, we used the dot . operator. But when
we have a pointer of structure type, we use arrow -> to access structure members.
#include <stdio.h>
struct my_structure {
char name[20];
int number;
int rank;
};
int main()
{
struct my_structure variable = {"StudyTonight", 35, 1};
struct my_structure *ptr;
ptr = &variable;
printf("NAME: %s\n", ptr->name);
printf("NUMBER: %d\n", ptr->number);
printf("RANK: %d", ptr->rank);
return 0;
}
NAME: StudyTonight
NUMBER: 35
RANK: 1

Compiled By : Deepak Kr. Singh, Pradip Khanal


Pointer Arithmetic
If you want to have complete knowledge of pointers, pointer arithmetic is very important to
understand. In this topic we will study how the memory addresses change when you increment a
pointer.
16 bit Machine (Turbo C)
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.
Size of datatypes on 16-bit Machine:
Type Size (in bytes)
int or signed int 2
Char 1
Long 4
Float 4
double 8
long double 10
Examples for Pointer Arithmetic
Now let's take a few examples and understand this more clearly.
int* i;
i++;
In the above case, pointer will be of 2 bytes. And when we increment it, it will increment by 2
bytes because int is also of 2 bytes.

float* i;
i++;
In this case, size of pointer is still 2 bytes initially. But now, when we increment it, it will
increment by 4 bytes because float data type is of 4 bytes.

double* i;
i++;
Similarly, in this case, size of pointer is still 2 bytes. But now, when we increment it, it will
increment by 8 bytes because its data type is double.

Compiled By : Deepak Kr. Singh, Pradip Khanal


32 bit Machine (Visual Basic C++)
The concept of pointer arithmetic remains exact same, but the size of pointer and various data
types is different in a 32 bit machine. Pointer in 32 bit machine is of 4 bytes.
And, following is a table for Size of data types on 32-bit Machine :

Type Size (in bytes)


int or signed int 4
Char 2
Long 8
Float 8
Double 16
Note: We cannot add two pointers. This is because pointers contain addresses, adding two
addresses makes no sense, because you have no idea what it would point to.
But we can subtract two pointers. This is because difference between two pointers gives the
number of elements of its data type that can be stored between the two pointers.
Program for pointer arithmetic(32-bit machine)
#include <stdio.h>
int main()
{
int m = 5, n = 10, o = 0;
int *p1;
int *p2;
int *p3;
p1 = &m; //printing the address of m
p2 = &n; //printing the address of n
printf("p1 = %d\n", p1);
printf("p2 = %d\n", p2);
o = *p1+*p2;
printf("*p1+*p2 = %d\n", o);//point 1
p3 = p1-p2;
printf("p1 - p2 = %d\n", p3); //point 2
p1++;
printf("p1++ = %d\n", p1); //point 3
p2--;
printf("p2-- = %d\n", p2); //point 4
//Below line will give ERROR
printf("p1+p2 = %d\n", p1+p2); //point 5
return 0;

Compiled By : Deepak Kr. Singh, Pradip Khanal


}
p1 = 2680016
p2 = 2680012
*p1+*p2 = 15
p1-p2 = 1
p1++ = 2680020
p2-- = 2680008

Explanation of the above program:


Point 1: Here, * means 'value at the given address'. Thus, it adds the value of m and n which is
15.
Point 2: It subtracts the addresses of the two variables and then divides it by the size of the
pointer data type (here integer, which has size of 4 bytes) which gives us the number of elements
of integer data type that can be stored within it.
Point 3: It increments the address stored by the pointer by the size of its data type(here 4).
Point 4: It decrements the address stored by the pointer by the size of its data type(here 4).
Point 5: Addition of two pointers is not allowed.

Pointers as Function Argument


Pointer as a function parameter is used to hold addresses of arguments passed during function
call. This is also known as call by reference. When a function is called by reference any change
made to the reference variable will affect the original variable.
Example Time: Swapping two numbers using Pointer
#include <stdio.h>
void swap(int *a, int *b);
int main()
{
int m = 10, n = 20;
printf("m = %d\n", m);
printf("n = %d\n\n", n);
swap(&m, &n); //passing address of m and n to the swap function
printf("After Swapping:\n\n");
printf("m = %d\n", m);
printf("n = %d", n);
return 0;
}
/*
pointer 'a' and 'b' holds and
points to the address of 'm' and 'n'
*/
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;}

Compiled By : Deepak Kr. Singh, Pradip Khanal


Output:
m = 10
n = 20
After Swapping:
m = 20
n = 10
Functions returning Pointer variables
A function can also return a pointer to the calling function. In this case you must be careful,
because local variables of function doesn't live outside the function. They have scope only inside
the function. Hence if you return a pointer connected to a local variable, that pointer will be
pointing to nothing when the function ends.
#include <stdio.h>
int* larger(int*, int*);
void main()
{
int a = 15;
int b = 92;
int *p;
p = larger(&a, &b);
printf("%d is larger",*p);
}
int* larger(int *x, int *y)
{
if(*x > *y)
return x;
else
return y;
}
92 is larger

Safe ways to return a valid Pointer.


 Either use argument with functions. Because argument passed to the functions are
declared inside the calling function, hence they will live outside the function as well.
 Or, use static local variables inside the function and return them. As static variables have
a lifetime until the main() function exits, therefore they will be available throughout the
program.

Pointer to functions
It is possible to declare a pointer pointing to a function which can then be used as an argument in
another function. A pointer to a function is declared as follows,
type (*pointer-name)(parameter);
Here is an example :
int (*sum)(); //legal declaration of pointer to function
int *sum(); //This is not a declaration of pointer to function
A function pointer can point to a specific function when it is assigned the name of that function.
int sum(int, int);

Compiled By : Deepak Kr. Singh, Pradip Khanal


int (*s)(int, int);
s = sum;
Here s is a pointer to a function sum. Now sum can be called using function pointer s along with
providing the required argument values.
s (10, 20);
Example of Pointer to Function
#include <stdio.h>
int sum(int x, int y)
{
return x+y;
}
int main( )
{
int (*fp)(int, int);
fp = sum;
int s = fp(10, 15);
printf("Sum is %d", s);
return 0;
}
25
Complicated Function Pointer example
You will find a lot of complex function pointer examples around, lets see one such example and
try to understand it.
void *(*foo) (int*);
It appears complex but it is very simple. In this case (*foo) is a pointer to the function, whose
argument is of int* type and return type is void*.

Q. What are the advantages of using pointer in C programming? Write a program in C to find
second largest elements from an array containing N elements using concept of pointer.
Q. What is string? WAP to read a 3x3 square matrix, find minimum integer value of a matrix,
replace the diagonal elements by the minimum elements and display it using pointer.
Q. If Ptr is a pointer to user defined type or basic type, by how many bytes is Ptr is incremented
when the statement Ptr++ is executed?
Q. WAP that calls reverse array() to reverse the array and return the array and display the
element of reversed array using pointer.
Q. Illustrate with example that "Array is indirectly a pointer" . WAP to calculate sum and
average of integer numbers between M and N (where value of M and N are read from keyboard)
using pointer.
Q. A pointer variable is used to store address of some other variables, however, we need to
specify data type while declaring a pointer variable. Why?
Q. Briefly explain array of pointers. How are array and pointers related? Give example.
Q. Compare array and pointer.

Compiled By : Deepak Kr. Singh, Pradip Khanal


Q. WAP to read a string from user and use a user defined function to copy the content of the read
string into another character array changing lower case letter to upper if any. Use pointer to
process the string.
Q. Explain call by reference. How are pointers used in call by reference?
Q. Using pointer concept, WAP to count the number of characters and the number of words in a
line of text entered by the user.
Q. What is NULL pointer? What will be the output of the following program, explain.
#include<stdio.h>
int main()
{
if(!NULL)
{
printf("C programming is easy.");
}
else
{
printf("C programming is not easy.")
}
return 0;
}
Output: C programming is easy.

Compiled By : Deepak Kr. Singh, Pradip Khanal

You might also like