C++Builder Learn To Use Arithmetics On Pointers In C++

FireWind

Свой
Регистрация
2 Дек 2005
Сообщения
1,957
Реакции
1,203
Credits
4,034
Learn To Use Arithmetics On Pointers In C++
By Yilmaz Yoru April 12, 2021

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,
C++:
int params[10];  // array with 10 integers, indexes are 0 to 10
param[0]=100;
param[1]=101;
 
int *p = &params[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.
C++:
int params[10];  // array with 10 integers, indexes are 0 to 10
int *p1 = &params;
int *p2 = &params[0];
 
if (p1==p2) std::cout << "they point the same address\n";
‘<‘ and ‘>’ comparison operators can be used in array pointers as given above.