In a previous post, we learned that pointers are variables to point address which is also an integer value. That means we can do arithmetic operations on a pointer variable. But do not forget that we operate on the addresses in our RAMs, so we should be careful and we should know the range well. Simply, we can use ++, –, +, and – arithmetic operators on pointers:
In a 32bit application, the pointer addresses 32bit. So the increment of pointer, when you increase the address 32bits, means that you increase that pointer to 4 bytes forward. If you decrease that pointer, it also means you decrease the address to 4 bytes backward. In a 64bits application, this means 64bits change that results in 8bits forward or backward address.
We can easily understand all these in this example below,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
int params[10]; // array with 10 integers, indexes are 0 to 10 param[0]=100; param[1]=101; int *p = ¶ms[0]; cout << "Address stored in pointer p: " << p << '\n'; cout << "Value of pointer variable : " << *p << '\n'; p++; // address increment cout << "Address stored in pointer p: " << p << '\n'; cout << "Value of pointer variable : " << *p << '\n'; p--; // address decrement cout << "Address stored in pointer p: " << p << '\n'; cout << "Value of pointer variable: " << *p << '\n'; |
Comparison in Pointers
Pointers are integer values that points address in memory, they can be also compared as integers by using relational operators such as ‘==’, ‘<‘, ‘>’. We can check two pointers if they are pointing the same address, see example below.
1 2 3 4 5 6 7 |
int params[10]; // array with 10 integers, indexes are 0 to 10 int *p1 = ¶ms; int *p2 = ¶ms[0]; if (p1==p2) std::cout << "they point the same address\n"; |
‘<‘ and ‘>’ comparison operators can be used in array pointers as given above.