0% found this document useful (0 votes)
5 views

Pointers

Uploaded by

2205009
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Pointers

Uploaded by

2205009
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Pointers in

C
CONTENTS
01 Introduction 03 Pointer to Pointer

02 Pointer Arithmetic
 Pointers are the heart of C programming. It is the most distinct feature of C, which
provides power and flexibility to C. Pointers separates C from other programming
languages.

C programmers make extensive use of pointers, because of their numerous benefits.


Below are some advantages of pointers.

 Pointers are more efficient in handling arrays and structures.


 Pointers are used to return multiple values from a function.
 We use pointers to get reference of a variable or function.
 Pointer allows dynamic memory allocation (creation of variables at runtime) in C.
Which undoubtedly is the biggest advantage of pointers.
 Pointers increases execution speed of program.

Pointers are closely related to low level memory operations. Hence, let us first
understand memory in contrast to C programming.
Understanding memory
Computer memory (RAM) is a collection of contiguous block of bytes. Where individual block is
called as cell (memory cell). Each cell has a unique numeric address (also known as physical
memory address) associated with it. These addresses starts from zero and runs up to maximum
memory size (in bytes).

For example, memory location of a 64KB RAM starts from 0 and ends to 65536 (or 0x10000)
bytes.
What happens during a variable definition.
Consider the statement int num = 10;

For the above statement, the C compiler allocates memory capable to store an integer. Let say
memory is allocated at address 0x1200.
After memory allocation, the C compiler defines a label (variable name) to access the memory
location. The label is mapped to the allocated memory.
Finally, the constant 10 is stored at 0x1200. Whenever you refer num inside your program,
internally C refers to the memory location of num.
What is a pointer?
A pointer is a variable that stores memory address. If it is a variable, it must have a
valid C data type. Yes, every pointer variable has a data type associated with it. Which
means an integer pointer can hold only integer variable addresses.

Note: We never say pointer stores or holds a memory location. Instead, we say pointer
points to a memory location. So from now always use the language pointer points to a
memory location.

Reference operator &


Because we are dealing with memory addresses, we must know how to get memory
address of a variable. We use unary & (reference of) operator to get memory address of
a variable. Reference operator is also known as address of operator.

Syntax to use reference of operator


&variable-name;
* C program to get memory address of a
variable

#include <stdio.h>

int main()
{
int num = 10;

printf("Value of num = %d\n", num);

/* &num gets the address of num. */


printf("Address of num = %d\n",
&num);

printf("Address of num in hexadecimal


= %x", &num);

return 0;
}
Dereference operator *

Once you have a memory address, you must be willing to get value
stored at that memory address, for that we need to dereference the
memory address.

Dereferencing is the process of retrieving value at memory location


pointed by a pointer. We use unary * dereference operator to get value
pointed by a memory address. Dereference operator is also known as
indirection operator.

Syntax to use dereference operator

*memory-address-or-pointer-variable;
* C program to use dereference operator

#include <stdio.h>

int main()
{
int num = 10;

printf("Value of num = %d\n", num);

/* &num gets the address of num. */


printf("Address of num = %d\n", &num);

/*
* &num gets the address of num
* and (*(&num)) gets value pointed by
(&num)
*/
printf("Value of num = %d\n", *(&num));

return 0;
}
How to declare pointer variable
Once you got basics of memory addresses, reference and dereference
operator. Let us declare our first pointer variable.

Pointer variable declaration follows almost similar syntax as of normal


variable.

Syntax to declare pointer variable

data-type * pointer-variable-name;

 data-type is a valid C data type.


 * symbol specifies it is a pointer variable. You must prefix * before
variable name to declare it as a pointer.
 pointer-variable-name is a valid C identifier i.e. the name of pointer
variable.
Example to declare pointer variable
int * ptr;
How to initialize pointer variable
There are two ways to initialize a pointer variable. You can use reference
operator & to get memory location of a variable or you can also directly
assign one pointer variable to other pointer variable.

Examples to initialize pointer variable

int num = 10;


int *ptr = &num; // Assign address of num to ptr

// You can also assign a pointer variable to another


int *ptr1 = ptr; // Initialize pointer using another pointer
How pointers are stored in memory
You got a basic picture of pointer working. Let us take a closer look on
how pointer variables are stored in memory. Consider the following
statements

int num = 10;


int *ptr = &num;
%x format specifier is used to
#include <stdio.h> /* Change the value of num
print hexadecimal
directly */
num = 10;
representation of a decimal.
int main()
{ printf("After changing value of
num directly. \n"); Output -
int num = 1;
printf("Value of num = %d \
int *ptr = &num; // ptr
n", num); Value of num = 1
points to num printf("Value pointed by ptr = Address of num = 60ff0c
%d \n\n", *ptr);
printf("Value of num = %d \
Value of ptr = 60ff0c
n", num);
/* Assigns 100 at the address Address of ptr = 60ff08
printf("Address of num = %x \
pointed by ptr */ Value pointed by ptr = 1
n\n", &num);
*ptr = 100;
printf("After changing value After changing value of num
pointed by ptr. \n"); directly.
printf("Value of ptr = %x \n", printf("Value of num = Value of num = 10
ptr); %d \n", num); Value pointed by ptr = 10
printf("Address of ptr = %x \ printf("Value pointed by ptr =
n", &ptr); %d \n", *ptr);
After changing value pointed by
printf("Value pointed by ptr =
return 0; ptr.
%d \n\n", *ptr);
} Value of num = 100
Value pointed by ptr = 100
Working of above program
int *ptr = &num; declares an integer pointer that points at num.
The first two printf() in line 12 and 13 are straightforward. First prints value of num and
other prints memory address of num.
printf("Value of ptr = %x \n", ptr); prints the value stored at ptr i.e. memory address of
num. Hence, the statement prints memory address of num.
printf("Address of ptr = %x \n", &ptr); prints the address of ptr.
Don't confuse with address of ptr and address pointed by ptr. First ptr is a variable so it
will have a memory address which is retrieved using &ptr. And since it is a pointer
variable hence it stores memory address which is retrieved using ptr.

printf("Value pointed by ptr = %d \n\n", *ptr);, here * dereferences value pointed by ptr
and prints the value at memory location pointed by ptr.
Next, we made some changes to num i.e. num=10. After changes printf("Value of num
= %d \n", num); prints 10.
Since we made changes to our original variable num, hence changes are reflected back
to pointer that points to the num. *ptr in line 23, dereferences value pointed by ptr i.e.
10.
*ptr = 100; says assign 100 to memory location pointed by ptr. Which means, assign
100 to num indirectly.
Since, we again modified the value of num using *ptr = 100. Hence, num and *ptr in
line 28 and 29 will evaluate to 100.
Pointer arithmetic in C programming

Pointer is a variable that points to a memory location. Memory addresses


are numeric value that ranges from zero to maximum memory size in
bytes. These addresses can be manipulated like simple variables. You
can increment, decrement, calculate or compare these addresses
manually.

C language provides a set of operators to perform arithmetic and


comparison of memory addresses. Pointer arithmetic and comparison in
C is supported by following operators -

Increment and decrement ++ and --


Addition and Subtraction + and -
Comparison <, >, <=, >=, ==, !=
Pointer increment and decrement
Increment operator when used with a pointer variable returns next address pointed by the pointer. The next
address returned is the sum of current pointed address and size of pointer data type.

Or in simple terms, incrementing a pointer will cause the pointer to point to a memory location skipping N
bytes from current pointed memory location. Where N is size of pointer data type.

Similarly, decrement operator returns the previous address pointed by the pointer. The returned address is the
difference of current pointed address and size of pointer data type.

For example, consider the below statements.

int num = 5; // Suppose address of num = 0x1230


int *ptr; // Pointer variable

ptr = &num; // ptr points to 0x1230 or ptr points to num


ptr++; // ptr now points to 0x1234, since integer size is 4 bytes
ptr--; // ptr now points to 0x1230
Note: Increment operation increments pointer address by the size of pointer data type.

If an integer pointer ptr pointing at 0x1230, after ptr++ it will point at 0x1234 (assuming integer size is 4
bytes).

If a character pointer cptr pointing at 0x1250, after cptr++ it will point at 0x1251 (since character occupies 1
byte).
#include <stdio.h>
#define SIZE 5

int main()
{
int arr[SIZE] = {10, 20, 30, 40, 50};
int *ptr;
int count;

ptr = &arr[0]; // ptr points to arr[0]

count = 0;

printf("Accessing array elements using


pointer \n");
while(count < SIZE)
{
printf("arr[%d] = %d \n", count, *ptr);

// Move pointer to next array element


ptr++;

count++;
}

return 0;
}
Pointer addition and subtraction
Pointer increment operation increments pointer by one. Causing it to
point to a memory location skipping N bytes (where N is size of pointer
data type).

We know that increment operation is equivalent to addition by one.


Suppose an integer pointer int * ptr. Now, ptr++ is equivalent to ptr = ptr
+ 1. Similarly, you can add or subtract any integer value to a pointer.

Adding K to a pointer causes it to point to a memory location skipping K *


N bytes. Where K is a constant integer and N is size of pointer data type.

Let us revise the above program to print array using pointer.


#include <stdio.h> When count = 0, (ptr + count) is
#define SIZE 5
equivalent to (ptr + 0) which points to
int main()
arr[0] and hence prints 10.
{ When count = 1, (ptr + count) is
int arr[SIZE] = {10, 20, 30, 40, 50}; equivalent to (ptr + 1) which points to
int *ptr; arr[1] and hence prints 20.
int count; Similarly when count = 4, (ptr + count)
is equivalent to (ptr + 4) which points
ptr = &arr[0]; // ptr points to arr[0] to arr[4] and hence prints 50.
count = 0;

printf("Accessing array elements


using pointer \n");
while(count < SIZE)
{
printf("arr[%d] = %d \n", count,
*(ptr + count));

count++;
}

return 0;
}
Pointer comparison
In C, you can compare two pointers using relational operator. You can
perform six different type of pointer comparison <, >, <=, >=, == and !
=.

Note: Pointer comparison compares two pointer addresses to which they


point to, instead of comparing their values.

Pointer comparisons are less used when compared to pointer arithmetic.


int main()
int main() {
{ int arr[5] = {10, 20, 30, 40, 50};
int num = 10; int *ptr = &arr[0]; // ptr points
int *ptr1 = &num; // ptr1 to arr[0]
points to num
int *ptr2 = &num; // ptr2 also while(ptr <= &arr[4])
points to num {
// ptr will always point within
if(ptr1 == ptr2) the array
{ // Do some task
// Both pointers points to
same memory location // Move ptr to next array
// Do some task element
} ptr++;
}
return 0;
} return 0;
}
Rules for performing pointer arithmetic
 Pointer arithmetic can be a nightmare if not used correctly. Incorrect pointer arithmetic will lead
to you compilation error as well as program crash.

Following are some rules that you must mind while performing pointer arithmetic.

 Result of two pointer addition or subtraction is an integer. For example,


int arr[] = {10, 20, 30, 40, 50};

int *ptr1 = &arr[0];


int *ptr2 = &arr[4];

int *ptr3 = ptr2 - ptr1; // ERROR -> (ptr2 - ptr1) evaluates to integer not integer pointer
Result of pointer and integer addition or subtraction is a pointer. For example,
int arr[] = {10, 20, 30, 40, 50};

int *ptr = &arr[0];

ptr = (ptr + 2); // ptr will now point to arr[2]

 You must not use multiplication and division operator with pointers.
Pointer to Pointer (Double Pointer) in C

We learned to create pointers and how to perform arithmetic operations


on them.

We learned to create pointers to int and char. In real, you can have
pointer to any type in C. You can have a pointer to int, char, float, double,
structure, array or even pointer. In fact, you can declare pointer to
pointer to pointer to pointer. That looks complex. For now, let us focus on
pointer to pointer.

If a pointer points to a pointer of same type, we call it as pointer to a


pointer.
How to declare pointer to pointer (double pointer)
Pointer to a pointer declaration follows same declaration
syntax as normal pointer declaration. The only thing you must
care is it contains two * asterisks.

In general increase number of * asterisks during pointer


declaration to increase pointer level.

Syntax to declare pointer to pointer


data-type ** pointer-variable-name;
Here double ** specifies it as pointer to pointer (double
pointer). Increase number of * asterisk with increase in
pointing levels. Means for pointer to pointer to pointer use ***.
Example to declare pointer to pointer
int ** ptr;
The above statement declares a pointer to integer pointer type.

How to initialize pointer to a pointer (double pointer)


Like declaration, pointer to pointer initialization is also similar to simple pointer initialization. However, you must be cautious
while initializing pointer to pointer. As it, accept address of a pointer variable of same type.

Example to initialize pointer to a pointer


int num = 10; // Integer variable
int *ptr = &num; // Pointer to integer

int **dPtr = &ptr; // Pointer to integer pointer


How to access pointer to a pointer
We use dereference * operator, to access value stored at memory location pointed by a pointer. However, single dereference
will not work when dealing with pointer to a pointer. In order to access value pointed by pointer to a pointer we use double
dereference ** (indirection) operator.

Example to access pointer to a pointer


int num = 10; // Declare an integer variable
int *ptr = &num; // Pointer to integer
int **dPtr = &ptr; // Pointer to integer pointer

printf("Value of dPtr = %d \n", dPtr); // Print value of dPtr, i.e address of ptr
printf("Value of ptr = %d \n", *dPtr); // Print value of ptr, i.e. address of num
printf("Value of num = %d \n", **dPtr); // Print value of num
C program to demonstrate use of
pointer to a pointer /* Assigns 100 using pointer to
*/ integer */
*ptr = 100;
#include <stdio.h> printf("Value of num = %d \n", Value of num = 10
num); Value pointed by ptr
int main() printf("Value pointed by ptr = = 10
{ %d \n", *ptr); Value pointed by
int num; // Integer variable printf("Value pointed by dPtr = dPtr = 10
%d \n\n", **dPtr); Value of num = 100
int *ptr = &num; // Pointer to Value pointed by ptr
integer = 100
int **dPtr = &ptr; // Pointer to /* Assigns 1000 using pointer to Value pointed by
integer pointer integer pointer */ dPtr = 100
**dPtr = 1000;
/* Change the value of num printf("Value of num = %d \n", Value of num =
1000
directly */ num);
Value pointed by ptr
num = 10; printf("Value pointed by ptr = = 1000
printf("Value of num = %d \n", %d \n", *ptr); Value pointed by
num); printf("Value pointed by dPtr = dPtr = 1000
printf("Value pointed by ptr = %d \n\n", **dPtr);
%d \n", *ptr);
printf("Value pointed by dPtr = return 0;
%d \n\n", **dPtr); }
THANK
S

You might also like