[go: up one dir, main page]

0% found this document useful (0 votes)
16 views27 pages

Unit 1 C Pointer Notes APC

The document provides an in-depth overview of pointers in the C programming language, detailing their definition, types, syntax, and usage. It covers various pointer types such as integer pointers, function pointers, and double pointers, along with their advantages and disadvantages. Additionally, it explains pointer arithmetic, memory allocation, and the relationship between pointers and arrays.

Uploaded by

anjaliparikh1306
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)
16 views27 pages

Unit 1 C Pointer Notes APC

The document provides an in-depth overview of pointers in the C programming language, detailing their definition, types, syntax, and usage. It covers various pointer types such as integer pointers, function pointers, and double pointers, along with their advantages and disadvantages. Additionally, it explains pointer arithmetic, memory allocation, and the relationship between pointers and arrays.

Uploaded by

anjaliparikh1306
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/ 27

APC Notes

Rakesh Pandit

C Pointers: -

Pointers are one of the core components of the C programming language.
A pointer can be used to store the memory address of other variables,
functions, or even other pointers. The use of pointers allows low-level
memory access, dynamic memory allocation, and many other functionality in C.
In this article, we will discuss C pointers in detail, their types, uses, advantages,
and disadvantages with examples.
What is a Pointer in C?
A pointer is defined as a derived data type that can store the address of other
C variables or a memory location. We can access and manipulate the data
stored in that memory location using pointers.
As the pointers in C store the memory addresses, their size is independent of the
type of data they are pointing to. This size of pointers in C only depends on the
system architecture.
Syntax of C Pointers
The syntax of pointers is similar to the variable declaration in C, but we use the (
* ) dereferencing operator in the pointer declaration.
datatype * ptr;
where
• ptr is the name of the pointer.
• datatype is the type of data it is pointing to.
The above syntax is used to define a pointer to a variable. We can also define
pointers to functions, structures, etc.
How to Use Pointers?
The use of pointers in C can be divided into three steps:
1. Pointer Declaration
2. Pointer Initialization
3. Pointer Dereferencing
1. Pointer Declaration
In pointer declaration, we only declare the pointer but do not initialize it. To
declare a pointer, we use the ( * ) dereference operator before its name.
Example
int *ptr;
The pointer declared here will point to some random memory address as it is not
initialized. Such pointers are called wild pointers.
2. Pointer Initialization
Pointer initialization is the process where we assign some initial value to the
pointer variable. We generally use the ( & ) addressof operator to get the
memory address of a variable and then store it in the pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;
APC Notes
Rakesh Pandit

We can also declare and initialize the pointer in a single step. This method is
called pointer definition as the pointer is declared and initialized at the same
time.
Example
int *ptr = &var;
Note: It is recommended that the pointers should always be initialized to some
value before starting using it. Otherwise, it may lead to number of errors.
3. Pointer Dereferencing
Dereferencing a pointer is the process of accessing the value stored in the
memory address specified in the pointer. We use the same ( * ) dereferencing
operator that we used in the pointer declaration.

Dereferencing a Pointer in C

C Pointer Example
• C

// C program to illustrate Pointers


#include <stdio.h>

void geeks()
{
int var = 10;

// declare pointer variable


int* ptr;

// note that data type of ptr and var must be same


ptr = &var;

// assign the address of a variable to a pointer


printf("Value at ptr = %p \n", ptr);
printf("Value at var = %d \n", var);
printf("Value at *ptr = %d \n", *ptr);
}
APC Notes
Rakesh Pandit

// Driver program
int main()
{
geeks();
return 0;
}

Output
Value at ptr = 0x7fff1038675c
Value at var = 10
Value at *ptr = 10

Types of Pointers in C
Pointers in C can be classified into many different types based on the parameter
on which we are defining their types. If we consider the type of variable stored in
the memory location pointed by the pointer, then the pointers can be classified
into the following types:
1. Integer Pointers
As the name suggests, these are the pointers that point to the integer values.
Syntax
int *ptr;
These pointers are pronounced as Pointer to Integer.
Similarly, a pointer can point to any primitive data type. It can point also point to
derived data types such as arrays and user-defined data types such as structures.
2. Array Pointer
Pointers and Array are closely related to each other. Even the array name is the
pointer to its first element. They are also known as Pointer to Arrays. We can
create a pointer to an array using the given syntax.
Syntax
char *ptr = &array_name;
Pointer to Arrays exhibits some interesting properties which we discussed later
in this article.
3. Structure Pointer
The pointer pointing to the structure type is called Structure Pointer or Pointer
to Structure. It can be declared in the same way as we declare the other primitive
data types.
Syntax
struct struct_name *ptr;
In C, structure pointers are used in data structures such as linked lists, trees, etc.
4. Function Pointers
Function pointers point to the functions. They are different from the rest of the
pointers in the sense that instead of pointing to the data, they point to the code.
Let’s consider a function prototype – int func (int, char), the function pointer for
this function will be
Syntax
int (*ptr)(int, char);
APC Notes
Rakesh Pandit

Note: The syntax of the function pointers changes according to the function
prototype.
5. Double Pointers
In C language, we can define a pointer that stores the memory address of another
pointer. Such pointers are called double-pointers or pointers-to-pointer. Instead
of pointing to a data value, they point to another pointer.
Syntax
datatype ** pointer_name;
Dereferencing Double Pointer
*pointer_name; // get the address stored in the inner level pointer
**pointer_name; // get the value pointed by inner level pointer
Note: In C, we can create multi-level pointers with any number of levels such as –
***ptr3, ****ptr4, ******ptr5 and so on.
6. NULL Pointer
The Null Pointers are those pointers that do not point to any memory location.
They can be created by assigning a NULL value to the pointer. A pointer of any
type can be assigned the NULL value.
Syntax
data_type *pointer_name = NULL;
or
pointer_name = NULL
It is said to be good practice to assign NULL to the pointers currently not in use.
7. Void Pointer
The Void pointers in C are the pointers of type void. It means that they do not
have any associated data type. They are also called generic pointers as they can
point to any type and can be typecasted to any type.
Syntax
void * pointer_name;
One of the main properties of void pointers is that they cannot be dereferenced.

Example
int *ptr;
char *str;
9. Constant Pointers
In constant pointers, the memory address stored inside the pointer is constant
and cannot be modified once it is defined. It will always point to the same
memory address.
Syntax
data_type * const pointer_name;
10. Pointer to Constant
The pointers pointing to a constant value that cannot be modified are called
pointers to a constant. Here we can only access the data pointed by the pointer,
but cannot modify it. Although, we can change the address stored in the pointer
to constant.
Syntax
const data_type * pointer_name;
Other Types of Pointers in C:
APC Notes
Rakesh Pandit

There are also the following types of pointers available to use in C apart from
those specified above:
• Far pointer: A far pointer is typically 32-bit that can access memory
outside the current segment.
• Dangling pointer: A pointer pointing to a memory location that has
been deleted (or freed) is called a dangling pointer.
• Huge pointer: A huge pointer is 32-bit long containing segment
address and offset address.
• Complex pointer: Pointers with multiple levels of indirection.
• Near pointer: Near pointer is used to store 16-bit addresses means
within the current segment on a 16-bit machine.
• Normalized pointer: It is a 32-bit pointer, which has as much of its
value in the segment register as possible.
• File Pointer: The pointer to a FILE data type is called a stream pointer
or a file pointer.
Size of Pointers in C
The size of the pointers in C is equal for every pointer type. The size of the
pointer does not depend on the type it is pointing to. It only depends on the
operating system and CPU architecture. The size of pointers in C is
• 8 bytes for a 64-bit System
• 4 bytes for a 32-bit System
The reason for the same size is that the pointers store the memory addresses, no
matter what type they are. As the space required to store the addresses of the
different memory locations is the same, the memory required by one pointer
type will be equal to the memory required by other pointer types.
How to find the size of pointers in C?
We can find the size of pointers using the sizeof operator as shown in the
following program:
Example: C Program to find the size of different pointer types.
// C Program to find the size of different pointers types
#include <stdio.h>

// dummy structure
struct str {
};

// dummy function
void func(int a, int b){};

int main()
{
// dummy variables definitions
int a = 10;
char c = 'G';
struct str x;
APC Notes
Rakesh Pandit

// pointer definitions of different types


int* ptr_int = &a;
char* ptr_char = &c;
struct str* ptr_str = &x;
void (*ptr_func)(int, int) = &func;
void* ptr_vn = NULL;

// printing sizes
printf("Size of Integer Pointer \t:\t%d bytes\n",
sizeof(ptr_int));
printf("Size of Character Pointer\t:\t%d bytes\n",
sizeof(ptr_char));
printf("Size of Structure Pointer\t:\t%d bytes\n",
sizeof(ptr_str));
printf("Size of Function Pointer\t:\t%d bytes\n",
sizeof(ptr_func));
printf("Size of NULL Void Pointer\t:\t%d bytes",
sizeof(ptr_vn));

return 0;
}

Output
Size of Integer Pointer : 8 bytes
Size of Character Pointer : 8 bytes
Size of Structure Pointer : 8 bytes
Size of Function Pointer : 8 bytes
Size of NULL Void Pointer : 8 bytes
As we can see, no matter what the type of pointer it is, the size of each and every
pointer is the same.
Now, one may wonder that if the size of all the pointers is the same, then why do
we need to declare the pointer type in the declaration? The type declaration is
needed in the pointer for dereferencing and pointer arithmetic purposes.

C Pointer Arithmetic(Operations on Pointers):-


The Pointer Arithmetic refers to the legal or valid arithmetic operations that can
be performed on a pointer. It is slightly different from the ones that we generally
use for mathematical calculations as only a limited set of operations can be
performed on pointers. These operations include:
• Increment in a Pointer
• Decrement in a Pointer
• Addition of integer to a pointer
• Subtraction of integer to a pointer
• Subtracting two pointers of the same type
• Comparison of pointers of the same type.
• Assignment of pointers of the same type.
APC Notes
Rakesh Pandit

// C program to illustrate Pointer Arithmetic

#include <stdio.h>

int main()
{

// Declare an array
int v[3] = { 10, 100, 200 };

// Declare pointer variable


int* ptr;

// Assign the address of v[0] to ptr


ptr = v;

for (int i = 0; i < 3; i++) {

// print value at address which is stored in ptr


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

// print value of ptr


printf("Value of ptr = %p\n\n", ptr);

// Increment pointer ptr by 1


ptr++;
}
return 0;
}

Output
Value of *ptr = 10
Value of ptr = 0x7ffe8ba7ec50

Value of *ptr = 100


Value of ptr = 0x7ffe8ba7ec54

Value of *ptr = 200


Value of ptr = 0x7ffe8ba7ec58
APC Notes
Rakesh Pandit

Pointers and Arrays: -


In C programming language, pointers and arrays are closely related. An array
name acts like a pointer constant. The value of this pointer constant is the
address of the first element. For example, if we have an array named val
then val and &val[0] can be used interchangeably.
If we assign this value to a non-constant pointer of the same type, then we can
access the elements of the array using this pointer.
Example 1: Accessing Array Elements using Pointer with Array
Subscript

// C Program to access array elements using pointer


#include <stdio.h>

void geeks()
{
// Declare an array
int val[3] = { 5, 10, 15 };

// Declare pointer variable


int* ptr;

// Assign address of val[0] to ptr.


// We can use ptr=&val[0];(both are same)
ptr = val;

printf("Elements of the array are: ");

printf("%d, %d, %d", ptr[0], ptr[1], ptr[2]);

return;
}

// Driver program
int main()
{
geeks();
return 0;
APC Notes
Rakesh Pandit

Output
Elements of the array are: 5 10 15
Not only that, as the array elements are stored continuously, we can pointer
arithmetic operations such as increment, decrement, addition, and subtraction of
integers on pointer to move between array elements.
Example 2: Accessing Array Elements using Pointer Arithmetic

// C Program to access array elements using pointers


#include <stdio.h>

int main()
{

// defining array
int arr[5] = { 1, 2, 3, 4, 5 };

// defining the pointer to array


int* ptr_arr = arr;

// traversing array using pointer arithmetic


for (int i = 0; i < 5; i++) {
printf("%d ", *ptr_arr++);
}
return 0;
}

Output
1 2 3 4 5
This concept is not limited to the one-dimensional array, we can refer to a
multidimensional array element as well using pointers.
APC Notes
Rakesh Pandit

Uses of Pointers in C
The C pointer is a very powerful tool that is widely used in C programming to
perform various useful operations. It is used to achieve the following
functionalities in C:
1. Pass Arguments by Reference
2. Accessing Array Elements
3. Return Multiple Values from Function
4. Dynamic Memory Allocation
5. Implementing Data Structures
6. In System-Level Programming where memory addresses are useful.
7. In locating the exact value at some memory location.
8. To avoid compiler confusion for the same variable name.
9. To use in Control Tables.
Advantages of Pointers
Following are the major advantages of pointers in C:
• Pointers are used for dynamic memory allocation and deallocation.
• An Array or a structure can be accessed efficiently with pointers
• Pointers are useful for accessing memory locations.
• Pointers are used to form complex data structures such as linked lists,
graphs, trees, etc.
• Pointers reduce the length of the program and its execution time as
well.
Disadvantages of Pointers
Pointers are vulnerable to errors and have following disadvantages:
• Memory corruption can occur if an incorrect value is provided to
pointers.
• Pointers are a little bit complex to understand.
• Pointers are majorly responsible for memory leaks in C.
• Pointers are comparatively slower than variables in C.
• Uninitialized pointers might cause a segmentation fault.

C – Pointer to Pointer (Double Pointer)


Pointers in C
The pointer to a pointer in C is used when we want to store the address of another
pointer.
The first pointer is used to store the address of the variable. And the second
pointer is used to store the address of the first pointer. That is why they are also
known as double-pointers.
We can use a pointer to a pointer to change the values of normal pointers or create
a variable-sized 2-D array. A double pointer occupies the same amount of space in
the memory stack as a normal pointer.
APC Notes
Rakesh Pandit

A pointer-to-pointer (double pointer) is used to store the address of another


pointer. The first pointer stores the address of a variable, and the second
pointer stores the address of the first pointer.

Declaration of Pointer to a Pointer in C


Declaring Pointer to Pointer is similar to declaring a pointer in C. The difference
is we have to place an additional ‘*’ before the name of the pointer.

data_type_of_pointer **name_of_variable = & normal_pointer_variable;


int val = 5;
int *ptr = &val; // storing address of val to pointer ptr.
int **d_ptr = &ptr; // pointer to a pointer declared
// which is pointing to an integer.
The above diagram shows the memory representation of a pointer to a pointer.
The first pointer ptr1 stores the address of the variable and the second pointer
ptr2 stores the address of the first pointer.
Example of Double Pointer in C
// C program to demonstrate pointer to pointer
#include <stdio.h>

int main()
{
int var = 789;

// pointer for var


int* ptr2;

// double pointer for ptr2


int** ptr1;

// storing address of var in ptr2


ptr2 = &var;

// Storing address of ptr2 in ptr1


ptr1 = &ptr2;

// Displaying value of var using


// both single and double pointers
printf("Value of var = %d\n", var);
printf("Value of var using single pointer = %d\n", *ptr2);
printf("Value of var using double pointer = %d\n", **ptr1);

return 0;
}
APC Notes
Rakesh Pandit

Output
Value of var = 789
Value of var using single pointer = 789
Value of var using double pointer = 789

How Double Pointer Works?

The working of the double-pointer can be explained using the above image:
• The double pointer is declared using the syntax shown above.
• After that, we store the address of another pointer as the value of this
new double pointer.
• Now, if we want to manipulate or dereference to any of its levels, we
have to use Asterisk ( * ) operator the number of times down the level
we want to go.
Size of Pointer to Pointer in C
In the C programming language, a double pointer behaves similarly to a normal
pointer in C. So, the size of the double-pointer variable is always equal to the
normal pointers. We can verify this using the below C Program.
Example 1: C Program to find the size of a pointer to a pointer.
// C program to find the size of pointer to pointer
#include <stdio.h>

int main()
{
// defining single and double pointers
int a = 5;
int* ptr = &a;
int** d_ptr = &ptr;

// size of single pointer


printf(" Size of normal Pointer: %d \n", sizeof(ptr));

// size of double pointer


printf(" Size of Double Pointer: %d \n", sizeof(d_ptr));

return 0;
}

Output
Size of normal Pointer: 8
Size of Double Pointer: 8
Note: The output of the above code also depends on the type of machine which is
being used. The size of a pointer is not fixed in the C programming language and
it depends on other factors like CPU architecture and OS used. Usually, for a 64-
APC Notes
Rakesh Pandit

bit Operating System, the size will be 8 bytes and for a 32-bit Operating system,
the size will be 4 bytes.
Application of Double Pointers in C
Following are the main uses of pointer to pointers in C:
• They are used in the dynamic memory allocation of multidimensional
arrays.
• They can be used to store multilevel data such as the text document
paragraph, sentences, and word semantics.
• They are used in data structures to directly manipulate the address of
the nodes without copying.
• They can be used as function arguments to manipulate the address
stored in the local pointer.
Multilevel Pointers in C
Double Pointers are not the only multilevel pointers supported by the C language.
What if we want to change the value of a double pointer?
In this case, we can use a triple pointer, which will be a pointer to a pointer to a
pointer i.e, int ***t_ptr.
Syntax of Triple Pointer
pointer_type *** pointer_name;

Pointer and Function; -


Function Pointer In C?
Function pointer in C is a variable which holds the address of a function. The function
pointers point to executable code inside a program, unlike regular pointers in C, which
point to data. The function pointers are used to get the address of the function. Let us
consider an example.

Function Pointer in C

void fun (int a )


{
printf(“ Rahul got %d marks in maths.\n”,mks);
}
int main ()
{

void (*ptr1) (int) = fun;


ptr1(20);
return 0;
}
In the above function, the fun pointer is a pointer pointing to a function name fun,
which will return an integer value at the end of execution.
APC Notes
Rakesh Pandit

Declaration of a Function Pointer in C


The function pointers contain the address of the function, which we can access using
pointers.

return data_type (*pointer_name) (parameter_type);

Let us take an example to understand the declaration of function pointers in C.

int add (int a, int b) {


return a + b;
}
int main ()
{
int (*functionPtr)(int, int);
functionPtr = add;
int result = functionPtr (2,3);
printf (“Result: %d\n”, result);
Output:

Result=5

Here, in the above example, we declare a ‘functionPtr’ that takes two parameters and
returns one. We then assign the address of the function ‘add’ to the pointer and then
call the add function by using the pointer directly.

Function Pointers in C Important Points


Let us now check some important facts related to function pointers in C.

full stack web development


• Function pointers are used to point to code, unlike regular pointers,
which point to data.
• With the help of function pointers, we can get the function address
using only the function’s name.
void fun (int a )
{
printf(“ Rahul got %d marks in maths.\n”,mks);
}
int main ()
{

void (*ptr1) (int) = fun;


ptr1(20);
return 0;
}
APC Notes
Rakesh Pandit

• We can use function pointers in switch case. Check the examples above
where we use a switch case based on the value of operation.
Function Pointer in C using Arrays
We can have an array of function pointers in C. Let us check an example of function
pointers using an array. The syntax for the function pointer array is

return _type (*functionPtr [SIZE]) (parameter_type)

Let us take an example to understand the array of function pointers in C.

#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a – b;
}
int multiply(int a, int b) {
return a * b;
}
int main() {
// Declare an array of function pointers
int (*functionPtrArray[3])(int, int) = {add, subtract, multiply};
// Call functions using function pointers
int result1 = functionPtrArray[0](3, 5);
int result2 = functionPtrArray[1](8, 2);
int result3 = functionPtrArray[2](4, 6);
printf(“Result 1: %d\n”, result1);
printf(“Result 2: %d\n”, result2);
printf(“Result 3: %d\n”, result3);
return 0;
}
Also read: Keywords and Identifiers in C

Output:

Result1: 8

Result2: 6

Result3: 24

Function Pointer in C using Pointer Variable


APC Notes
Rakesh Pandit

We can pass pointers as function arguments in C and can return the pointers from
the function. We can pass a reference to the value stored instead of passing the value
stored inside the variable. This is called pass by reference.

#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a – b;
}
int main() {
int (*functionPtr)(int, int);
int a = 10, b = 5;
char operation = ‘+’;
if (operation == ‘+’) {
functionPtr = add;
}

else if (operation == ‘-‘) {


functionPtr = subtract;
}
else {
printf(“Invalid operation\n”);
return 1;
}
int result = functionPtr(a, b);
printf(“Result: %d\n”, result);
return 0;
}
Here, we use a function pointer variable named ‘functionPtr’, which can point to
either addition or subtraction. If the value of the operation is ‘+’, then it performs
addition, and if it is ‘-’, it performs subtraction. It assigns the appropriate function to
the pointer using conditional statements.

Output:

Result: 15

How to Reference and Derefernce A Pointer in C


Function pointer in C is used to assign the address of a function and can call the
function directly with the help of these pointers. If we want to reference a pointer,
we need to assign the address of the function. The pointer will store the address of
the function.

int add(int a, int b) {


return a + b;
APC Notes
Rakesh Pandit

}
int (*functionPtr)(int, int);
functionPtr = add;
But when we want to dereference a function pointer then we only need to call the
function pointer, just like we call a function. You need to provide the necessary
arguments to the function pointer to deference it.

int result = functionPtr (2, 3);


printf (“Result: %d\n”, result); //
Output: Result: 5
After providing the arguments to the function pointer, it will call the function and
compute the code. The output result will be 5 in the above case.

Function Pointer Example


Let us understand the function pointer using the example given here in the table.
Here, we use function pointers to find the addition, subtraction, multiplication or
division of two numbers based on the value of the operation variable.

#include <stdio.h>
// Function prototypes for operations
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
int divide(int a, int b);
int main() {
int (*operation)(int, int);
int a, b, result;
char operator;
printf(“Enter operation (+, -, *, /): “);
scanf(” %c”, &operator);
switch (operator) {
case ‘+’:
operation = add;
break;
case ‘-‘:
operation = subtract;
break;
case ‘*’:
operation = multiply;
break;
case ‘/’:
operation = divide;
Break;
default:
printf(“Invalid operation\n”);
return 1;
}
APC Notes
Rakesh Pandit

printf(“Enter two numbers: “);

scanf(“%d %d”, &a, &b);


result = operation(a, b);
printf(“Result: %d\n”, result);
return 0;
}
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a – b;
}
int multiply(int a, int b) {
return a * b;
}
int divide(int a, int b) {
if (b != 0) {
return a / b;
} else {
printf(“Error: Division by zero\n”);
return 0;
}
}

Advantage of Function Pointer in C


Function Pointer in C has many benefits. Let us check out some of the major
advantages of Function pointers.

• Function pointers are used to store the address of the function and
point them whenever needed. Hence, they make the callback
mechanism easy. You can easily pass a function as an argument in C.
• They make the program simple and short.
• Function pointers are used in a program to enhance the flexibility of a
program.
• Function pointers make our code safe.
• We can select functions dynamically at runtime based on various
conditions.
APC Notes
Rakesh Pandit

What are different pointer operations


and problems with pointers in C
language?

A pointer is a variable whose value is the address of an another variable, i.e.,


direct address of the memory location. Like any variable or constant, you must
declare a pointer before using it to store any variable address.

Consider the following statement −

int qty = 179;

The representation of the variable in memory is as follows −

You can declare a pointer as follows −


Int *p;
It means ‘p’ is a pointer variable that holds the address of another integer
variable.
Address operator (&) is used to initialize a pointer variable.
For Example −
int qty = 175;
int *p;
p= &qty;
APC Notes
Rakesh Pandit

To access the value of the variable, indirection operator (*) is used.

For example −

‘*’ can be treated as value at address.

The two statements are equivalent to the following statement −

p = &qty;
n = *p; n =qty

Different pointer operations


The pointer operations in C language are explained below −

• Assignment − We can assign an address to a pointer by using & (address operator).


• Value finding − It is nothing but dereferencing, where the * operator gives the value
stored in the pointed to location.
• Taking a pointer address − Just like other variables, pointer variables have an
address as well as a value, with the help of address operator we can find were the
pointer itself is stored.
• Adding an integer to a pointer − We can use + operator to add an integer to a pointer
or a pointer to an integer. Here, in both the cases the int is multiplied with the no of
bytes in the pointed to type, and the result is added to original address.
APC Notes
Rakesh Pandit

• Incrementing a pointer − It is an array element that makes to move to the next


element of the array.
• Subtracting an int from a pointer − We are using – (minus) operator to subtract an
integer from a pointer. The integer is multiplied with the number of bytes in pointed
to type, and the result is subtracted from original address.
• Decrementing a pointer − Decrementing pointer, points to previous location instead
of before, we can use both pre and postfix form for decrement operator.
• Subtraction − We can find difference of two pointers. Generally, we used to find out
how apart the elements are.
• Comparison − We will use relational operator to compare the values of two pointers.

Example
Given below is the program to demonstrate the functioning of the pointer
operations in C language −

#include<stdio.h>
main ( ){
int x,y;
//Declaring a pointer
int *p;
clrscr ( );
x= 10;
//Assigning value to a pointer
p = &x;
y= *p;
printf ("Value of x = %d", x);
printf ("x is stored at address %u", &x);
printf ("Value of x using pointer = %d", *p);
printf ("address of x using pointer = %u", p);
printf (“value of x in y = %d", y);
*p = 25;
printf ("now x = %d", x)
getch ( );
}

Output
When you execute the above mentioned program, you get the following output

Value of x = 10
x is stored at address = 5000
Address of x using pointer = 10
APC Notes
Rakesh Pandit

Address of x using pointer = 5000


Value of x in y = 10
Now x = 25

Arithmetic Operations on Pointers in C Language


with Examples
Arithmetic Operations on Pointers in C:
Pointer variable stores another variable’s address. The address is nothing but the memory
location assigned to the variable. That means the pointer doesn’t store any value. It stores
the address. Hence, only a few operations are allowed to be performed on Pointers. The
operations are slightly different from those we generally use for mathematical calculations.
The operations are as follows:
1. Increment/Decrement of a Pointer
2. Addition of integer to a pointer
3. Subtraction of integer to a pointer
4. Subtracting two pointers of the same type
Increment/Decrement Operation of a Pointer in C Language
Increment: When a pointer is incremented, it actually increments by the number equal to
the size of the data type for which it is a pointer. For Example, If the pointer is of type
integer and the pointer stores address 1000 and if the pointer is incremented, it will
increment by 2(size of an int), and the new address that the pointer will point to is 1002. If
the pointer is of type float and stores the address 1000, and if the pointer is incremented,
it will increment by 4(size of a float), and the new address will be 1004.
Advertisements

Decrement: It is just the opposite of the Increment operation. When a pointer is


decremented, it actually decrements by the number equal to the size of the data type for
which it is a pointer. For Example, If the pointer is of type integer and if the pointer stores
the address 1000, and if the pointer is decremented, then it will decrement by 2(size of an
int), and the new address that the pointer will point to is 998. If the pointer is of type float
and if it stores the address 1000, and if the pointer is decremented, then it will decrement
by 4(size of a float), and the new address will be 996.
Program to Understand Increment/Decrement Operation of a Pointer in C
The following program illustrates pointer increment/decrement
operation using C Language.
#include <stdio.h>
int main ()
{
// Integer variable
int a = 10, b=20;

// Pointer to an integer
int *ptr1, *ptr2;

// Pointer stores the address of variable a


ptr1 = &a;
ptr2 = &b;
APC Notes
Rakesh Pandit

printf ("Pointer ptr1 before Increment: ");


printf ("%p \n", ptr1);

// Incrementing pointer ptr1;


ptr1++;

printf ("Pointer ptr1 after Increment: ");


printf ("%p \n\n", ptr1);

printf ("Pointer ptr2 before Decrement: ");


printf ("%p \n", ptr2);

// Decrementing pointer ptr2;


ptr2--;

printf ("Pointer ptr2 after Decrement: ");


printf ("%p \n\n", ptr2);

return 0;
}

Output:

Addition and Subtraction Arithmetic Operation on Pointer in C Language


Let us see how to perform Addition and Subtraction Operations on a Pointer in C
Language.
Advertisements

1. Addition: In C Programming Language, when a pointer is added with a


value, the value is first multiplied by the size of the data type and then added
to the pointer.
2. Subtraction: In C Programming Language, when a pointer is subtracted
with a value, the value is first multiplied by the size of the data type and then
subtracted from the pointer.
The following program illustrates Addition and Subtraction Arithmetic Operations on a
Pointer in C Language.

#include <stdio.h>
int main()
{
// Integer variable
int a = 10;
APC Notes
Rakesh Pandit

// Pointer to an integer
int *ptr1, *ptr2;

// Pointer stores the address of variable a


ptr1 = &a;
ptr2 = &a;

printf("Pointer ptr1 before Addition: ");


printf("%p \n", ptr1);

// Addition of 2 to pointer ptr1


ptr1 = ptr1 + 2;
printf("Pointer ptr1 after Addition: ");
printf("%p \n", ptr1);

printf("Pointer ptr2 before Subtraction : ");


printf("%p \n", ptr2);

// Subtraction of 2 from pointer ptr2


ptr2 = ptr2 + 2;
printf("Pointer ptr1 after Subtraction : ");
printf("%p \n", ptr2);
return 0;
}
Output:

Addition and Subtraction of Two Pointers in C Language


In the example below, we created two integer pointers and then performed the addition
and subtraction operation.

#include<stdio.h>
int main ()
{
int a = 30, b = 10, *p1, *p2, sum;
p1 = &a;
p2 = &b;
sum = *p1 + *p2;
printf ("Addition of two numbers = %d\n", sum);
sum = *p1 - *p2;
printf ("Subtraction of two numbers = %d\n", sum);
return 0;
}
APC Notes
Rakesh Pandit

Output:

Arithmetic Operations on Pointers in C


In C programming, pointers are variables that store the memory addresses of other
variables. Arithmetic operations on pointers can be quite useful, especially in array
manipulation and dynamic memory management. Let’s discuss the various arithmetic
operations that can be performed on pointers:
• Pointer Increment (++): Incrementing a pointer advances it to point to the
next element of its type. For example, if int *p points to an integer, p++ will
increase p so it points to the next integer in memory (typically 4 bytes ahead
on a system where int is 4 bytes).
• Pointer Decrement (–): Decrementing a pointer does the opposite of
incrementing. It makes the pointer point to the previous element of its type.
• Pointer Addition: You can add an integer value to a pointer. If p is a
pointer and n is an integer, p + n increments p to point to the nth element
ahead. This does not change the value of p itself unless you assign the
result to p.
• Pointer Subtraction: Subtracting an integer from a pointer, as in p – n,
moves the pointer n elements back.
• Subtracting Two Pointers: When you subtract one pointer from another,
as in p1 – p2, the result is the number of elements between the two pointers,
assuming both pointers point to elements of the same array.
• Comparing Pointers: Pointers can be compared using relational
operators like ==, !=, >, <, >=, and <=. This can be useful to check if two
pointers point to the same location or to determine the relative positions of
pointers in the same array.
Let’s go through some examples of arithmetic operations using pointers in C. These
examples will help illustrate how pointer arithmetic works in different scenarios.
Example 1: Pointer Increment

#include <stdio.h>

int main() {
int arr[] = {10, 20, 30, 40, 50};
int *p = arr; // Pointer to the first element of the array

printf("Original address: %p, Value: %d\n", (void*)p, *p);


p++; // Increment the pointer
printf("New address: %p, Value: %d\n", (void*)p, *p);

return 0;
}

In this example, p initially points to the first element of arr. After the increment (p++), p
points to the second element.
APC Notes
Rakesh Pandit

Advertisements

Example 2: Pointer Decrement


#include <stdio.h>

int main() {
int arr[] = {10, 20, 30, 40, 50};
int *p = &arr[3]; // Pointer to the fourth element of the
array

printf("Original address: %p, Value: %d\n", (void*)p, *p);


p--; // Decrement the pointer
printf("New address: %p, Value: %d\n", (void*)p, *p);

return 0;
}

Here, p is set to point to the fourth element of arr. After decrementing (p–), it points to the
third element.
Example 3: Pointer Addition
#include <stdio.h>

int main() {
int arr[] = {10, 20, 30, 40, 50};
int *p = arr; // Pointer to the first element

// Move the pointer 2 elements forward


p = p + 2;
printf("Address: %p, Value: %d\n", (void*)p, *p);

return 0;
}

In this case, p + 2 moves the pointer p two elements forward, so it points to the third
element (30).
Example 4: Pointer Subtraction
#include <stdio.h>

int main() {
int arr[] = {10, 20, 30, 40, 50};
int *p = &arr[4]; // Pointer to the last element

// Move the pointer 2 elements back


p = p - 2;
printf("Address: %p, Value: %d\n", (void*)p, *p);

return 0;
}

p – 2 moves the pointer p two elements back, pointing it to the third element from the last.

Example 5: Subtracting Two Pointers


#include <stdio.h>
APC Notes
Rakesh Pandit

int main() {
int arr[] = {10, 20, 30, 40, 50};
int *p1 = &arr[4]; // Pointer to the last element
int *p2 = arr; // Pointer to the first element

int diff = p1 - p2;


printf("Difference in elements: %d\n", diff);

return 0;
}
This example calculates the difference between two pointers, p1 and p2, which is the
number of elements between them in the array.

You might also like