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.
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 |
Now lets 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
datatype 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
.
The concept of pointer arithmetic remains exact same, but the size of pointer and various datatypes is different in a 32 bit machine. Pointer in 32 bit machine is of 4 bytes.
And, following is a table for Size of datatypes 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.
#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;
}
p1 = 2680016 p2 = 2680012 *p1+*p2 = 15 p1-p2 = 1 p1++ = 2680020 p2-- = 2680008
*
means 'value at the given address'. Thus, it adds the value of m and n which is 15.