« Pointers Arithmetic
Understand pointers arithmetic in 10 minutes
Step 1: Size of pointers
1int *p;2char *q;3double *r;4float *s;5cout << sizeof(p) << endl6<< sizeof(q) << endl7<< sizeof(r) << endl8<< 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
.
1a++; //move to the next integer2a--; //move to the pervious integer3a = a + 2; //move to 2 integers ahead
Pointer arithmetic makes sense only in the case of arrays
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_MIN11#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) << endl20 << sizeof(q) << endl21 << sizeof(r) << endl22 << sizeof(s) << endl;2324 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.2930 cout << "a: " << a << endl;31 a++; // move to the next integer32 a--; // move to the pervious integer33 a = a + 2; // move to 2 integers ahead3435 double d = 12.2;36 double *dp = &d;37 cout << "dp: " << dp << endl;38 dp++; // This means move to the next double39 cout << "dp: " << dp << endl;4041 return 0;42}