Sometimes we need to perform arithmetic operations on pointers. But before using arithmetic operators with pointers we need to understand that we can not use each arithmetic operators with pointers. Pointer arithmetic is slightly different from arithmetic we normally use in our daily life.
We also need to remember that we cannot use the multiplication or division operator with the pointer. Below I am mentioning some arithmetic operations with pointers.
Indirection (*) | This operator is used to get the value from the pointed address. |
Reference operator (&) | This operator is used to get the address of the variable or pointer. |
Assignment (=) | You can assign the value to the pointer or value to the address which is pointed by the pointer. |
Addition (+) | You can add integer value to the pointer to point the different memory locations. |
Subtraction (-) | You can subtract the integer value from the pointer to point the different memory locations. |
comparison (==, !=, <, >, <=, and >=) | This operation is valid only between two pointers that point to the same array. |
Incrementing (++) | You can use increment operators (pre and post) with the pointer. |
Decrementing (–) | You can use decrement operators (pre and post) with the pointer. |
Note: When we increment or decrement the pointer then pointer increase or decrease a block of memory (block of memory depends on pointer data type).
How does pointer arithmetic work
When we increment or decrement the pointer then pointer point to the next or previous memory location. Generally, people make mistakes, when they calculate the next pointing address of the pointer.
Here is the technique to calculate the next pointing address of a pointer when applying arithmetic operation on it. To understand this technique let us consider ptr is a pointer has data type “T” and “i” is the pointer offset.
addr( ptr + i ) = addr( ptr ) + ( sizeof( T ) * i ); addr( ptr - i ) = addr( ptr ) - ( sizeof( T ) * i );
Pointer Arithmetic on Character Pointer:
If we increment the character pointer by 1 then it will point to the address which will be just 1 byte more to the current pointing address. Let us see an example where pcData is a character pointer and we performing an arithmetic operation on it.
char *pcData =NULL;
When we increment the pcData then it points to the next character location without impacting the stored data. The size of the character is 1 byte that’s why pointer moves only 1 byte of memory. .
pcData++;
So let us see how is the above technique work here to calculate the next pointing address.
addr( pcData + 1 ) = addr( pcData ) + [ sizeof( char ) * 1 ]; addr( pcData + 1 ) = addr( pcData ) + [ 1 * 1 ]; addr( pcData + 1 ) = addr( pcData ) + 1;
You can see that the next pointing address only 1 byte more to the current pointing address because the size of the character is 1 byte.
When you perform arithmetic subtraction on pointer then you have to use the second technique which describes in the beginning. The basic concept will be the same difference is only that here you need to subtract the calculated offset from the pointing address.
Similar to that If we add 2 to the pcData (character pointer ) then pcData will point to the next 2 bytes of the current pointing position.
char *pcData = NULL; pcData = pcData + 2;
In this table, we have summarized the arithmetic operation on the character pointer. So pcData is a character pointer and suppose initially it points to an address “3000”.
Pointer Expression |
How it is evaluated ? |
pcData + 1 |
pcData = pcData + 1 => 3000 + 1*1 => 3001 |
pcData++ or ++pcData |
pcData => pcData + 1 => 3000 + 1*1 => 3001 |
pcData = pcData + 5 |
pcData => pcData + 5 => 3000 + 5*1 => 3005 |
pcData = pcData – 2 |
pcData => pcData – 2 => 3000 – 2*1 => 2998 |
pcData– or –pcData |
pcData => pcData – 1 => 3000 – 1*1 => 2999 |
Pointer Arithmetic on Float Pointer:
Like the character pointer, when we increment the float pointer then it points to the next float location without impacting the stored data. Let us see an example where pfData is a float pointer and we performing an arithmetic operation on it.
float *pfData = NULL;
When we increment the pfData then it points to the next float location without impacting the stored data. Here we are assuming float size is 4 bytes. So when we increment the float pointer by 1 then it will point to the address which will be just 4 bytes more to the current pointing address.
pfData++;
So let us see how is the above technique work here to calculate the next pointing address for the float pointer.
addr( pfData + 1 ) = addr( pfData ) + [ sizeof( float) * 1 ]; addr( pfData + 1 ) = addr( pfData ) + [ 4 * 1 ]; addr( pfData + 1 ) = addr( pfData ) + 4;
Similar to that If we add 2 to the pfData (float pointer size 4 byte ) then pfData will point to the next 8 bytes of the current pointing position.
float *pfData = NULL; pfData = pfData + 2;
In this table, we have summarized the arithmetic operation on the float pointer. So pfData is a float pointer and supposes that initially, it points to an address “2000”.
Pointer Expression |
How it is evaluated ? |
pfData + 1 |
pfData = pfData + 1 => 2000 + 1*4 => 2004 |
pfData++ or ++pfData |
pfData++ => pfData + 1 => 2000 + 1*4 => 2004 |
pfData = pfData + 5 |
pfData => pfData + 5 => 2000 + 5*4 => 2020 |
pfData = pfData – 2 | pfData => pfData – 2 => 2000-2*4 => 1992 |
pfData– or –pfData | pfData => pfData – 1 => 2000-1*4 => 1996 |
Program to increment a pointer in C
In the below program, I am creating a character and float pointer and incrementing the pointer by 1 using the increment operator. After performing the arithmetic operation on pointer I am printing the address which is pointing by pointers.
#include <stdio.h> #include <stdlib.h> int main() { char *pcData = NULL; //pointer to character float *pfData = NULL; // pointer to float printf(" Address of character pointer before incrementation = %d\n\n\n", pcData); printf(" Address of float pointer before incrementation = %d\n\n\n", pfData); pcData++; //Increment the character pointer by one pfData++; //Increment the float pointer by one printf(" Address of character pointer After incrementation = %d\n\n\n", pcData); printf(" Address of float pointer After incrementation = %d\n\n\n", pfData); return 0; }
Output:
#include <stdio.h> #include <stdlib.h> int main() { char *pcData = NULL; //pointer to character float *pfData = NULL; // pointer to float printf("\n\n Address of character pointer before incrementation = %d\n\n\n", pcData); printf(" Address of float pointer before incrementation = %d\n\n\n", pfData); pcData = pcData + 2; //Increment the character pointer by one pfData = pfData + 2; //Increment the float pointer by one printf(" Address of character pointer After incrementation = %d\n\n\n", pcData); printf(" Address of float pointer After incrementation = %d\n\n\n", pfData); return 0; }
If you want to learn more about the C language, here 10 Free days (up to 200 minutes) C video course for you.
Your free trial is waiting
Pointers subtraction in C
We can also subtract one pointer from another pointer. This technique is useful when we need to calculate the number of bytes between the two pointers. But pointers subtraction is useful when they are pointing the same array or memory block.
If subtract two pointers that pointing the same array, the result of this subtraction gives the number of elements that separate them. Let’s consider two examples which describe the subtraction of two number.
Example 1:
In this example, we will calculate the size of the structure to subtract the pointers.
#include <stdio.h> #include <stdlib.h> typedef struct { int Age; float Weight; } sInfo; int main() { //create an array of structure; sInfo JhonFamilyInfo[2]; //Create pointer to the structure sInfo *psInfo = NULL; int iSizeofStructure = 0; //Assign the address of array to the pointer psInfo = JhonFamilyInfo; // Subtract the pointer iSizeofStructure = (char*)(psInfo + 1) - (char*)(psInfo); printf("Size of structure = %d\n\n",iSizeofStructure); return 0; }
Output: Size of structure = 8
Example 2:
In this example, we will calculate the number of elements that are separating the pointers or you can say that calculating the pointer offset.
#include <stdio.h> #include <stdlib.h> int main() { //create an array of structure; int aiData[] = {1,2,3,4,5}; //Create two pointer to the integer int *piData1 = NULL; int *piData2 = NULL; int iOffset = 0; //Assign the address of array first element to the pointer piData1 = &aiData[0]; //Assign the address of array third element to the pointer piData2 = &aiData[2]; // Subtract the pointer iOffset = piData2 - piData1; printf("pointer offset = %d\n\n",iOffset); return 0; }
Output: pointer offset = 2.
Note: There are is no meaning to the addition of two pointers.
Pointer comparison in C
Like the pointer subtraction, we can also compare the pointer but pointer should be pointed to the same array or memory block.
See the below example;
char acBuffer[10] = “aticleworld”; char *pc1, *pc2;
Assigning address of first and third elements of acBuffer1 to pc1 and pc2.
pc1 = &acBuffer[0]; // Address of first element pc2 = &acBuffer[2]; // Address of third element Now we can compare the pointers if required. if( pc1 > pc2) // Legal statement { }
But pointers comparison is invalid when pointers point to the 2 different memory blocks.
See the below example;
char acBuffer1[10] = “aticle”; char acBuffer2[10] = “world”; char *pc1, *pc2;
Assigning the address of acBuffer1 to pc1 and acBuffer2 to the pc2.
pc1 = acBuffer1; pc2 = acBuffer2;
In that situation pointer comparison is invalid.
if( pc1 > pc2) // illegal statement { }
Note: The C standard does not allow the arithmetic operation on void pointers but GNU C allows with assuming the size of the void is 1. To know about the void pointer See this Link: Use of void pointer in C language.
Indirection and Increment/Decrement operators with a pointer:
We can combine the indirection operator (*) with increment/decrement (++ , — )operators. Let’s see some example C codes to understand the behavior of the indirection and increment/decrement operators.
Indirection operator with pre-increment operator:
#include <stdio.h> int main(void) { int aiData[5] = {100,200,300,400,500}; int *piData = aiData; ++*piData; printf("aiData[0] = %d, aiData[1] = %d, *piData = %d", aiData[0], aiData[1], *piData); return 0; }
Output: 101 , 200 , 101
Explanation:
In the above example, two operators are involved and both have the same precedence with a right to left associativity. So the above expression ++*p is equivalent to ++ (*p). In another word, we can say it is pre-increment of value and output is 101, 200, 101.
#include <stdio.h> int main(void) { int aiData[5] = {100,200,30,40,50}; int *piData = aiData; *++piData; printf("aiData[0] = %d, aiData[1] = %d, *piData = %d", aiData[0], aiData[1], *piData); return 0; }
Output: 100, 200, 200
Explanation:
In the above example, two operators are involved and both have the same precedence with the right to left associativity. So the above expression *++p is equivalent to *(++p). In another word you can say it is pre-increment of address and output is 100, 200,200.
Indirection operator with post-increment operator:
#include <stdio.h> int main(void) { int aiData[5] = {100,200,30,40,50}; int *piData = aiData; *piData++; printf("aiData[0] = %d, aiData[1] = %d, *piData = %d", aiData[0], aiData[1], *piData); return 0; }
Output: 100, 200, 200
Explanation:
In the above example, two operators are involved and both have different precedence. The precedence of post ++ is higher than the *, so first post ++ will be executed and above expression, *p++ will be equivalent to *(p++). In another word you can say that it is post-increment of address and output is 100, 200, 200.
Recommended Articles for you:
- How to create dynamic array in C?
- 15 Common mistakes with memory allocation.
- How to access 2d array in C?
- A brief description of the pointer in C.
- Dangling, Void, Null and Wild Pointers
- Function pointer in c, a detailed guide
- How to use the structure of function pointer in c language?
- Memory Layout in C.
- 100 embedded C interview Questions.
- Python Interview Questions with Answer.
- File handling in C.
- Function pointer in structure.
- void pointer in C, A detail discussion.
- 100 c interview questions, your interviewer might ask.
- File handling in C.
- C format specifiers.