« Pointers Arithmetic

Understand pointers arithmetic in 10 minutes

Step 1: Size of pointers

1int *p;
2char *q;
3double *r;
4float *s;
5cout << sizeof(p) << endl
6<< sizeof(q) << endl
7<< sizeof(r) << endl
8<< sizeof(s) << endl;

Generally these all will come same but it depends on compiler these value might come different. But all these variables just need to store addresses so these should generally come same.

Step 2: Pointers increment and decrement

1int i = 10;
2int *a = &i;
3cout << "a: " << a << endl;
4a = a + 1;

This doesn't adds 1 to the address, but this means we want to move to the next integer. As sizeof(int) is 4 so a+1 will add 4 to the address stored at a.

p_plus_1.jpg

1a++; //move to the next integer
2a--; //move to the pervious integer
3a = a + 2; //move to 2 integers ahead

Pointer arithmetic makes sense only in the case of arrays

pointer_arithmetic.jpg

1double d = 12.2;
2double *dp = &d;
3cout << "dp: " << dp << endl;
4dp++;
5cout << "dp: " << dp << endl;

Above means move to the next double so it will add 8 to the address stored at dp as sizeof(double) is 8

Final code

1#include <iostream>
2#include <iomanip>
3#include <algorithm>
4#include <string>
5#include <cstring>
6#include <vector>
7#include <cmath>
8#include <map>
9#include <climits>
10// climits for INT_MIN
11#include <unordered_map>
12using namespace std;
13int main()
14{
15 int *p;
16 char *q;
17 double *r;
18 float *s;
19 cout << sizeof(p) << endl
20 << sizeof(q) << endl
21 << sizeof(r) << endl
22 << sizeof(s) << endl;
23
24 int i = 10;
25 int *a = &i;
26 cout << "a: " << a << endl;
27 a = a + 1;
28 // a + 1 will add 4 to the address stored at a.
29
30 cout << "a: " << a << endl;
31 a++; // move to the next integer
32 a--; // move to the pervious integer
33 a = a + 2; // move to 2 integers ahead
34
35 double d = 12.2;
36 double *dp = &d;
37 cout << "dp: " << dp << endl;
38 dp++; // This means move to the next double
39 cout << "dp: " << dp << endl;
40
41 return 0;
42}