The pointers are simply integers of the size of the microprocessor data bus.
For example, in micro architectures x86 sizeof(int) == sizeof(void*)
, this means that a pointer is simply an integer (without a sign).
In micro architectures x86_64 sizeof(long long) == sizeof(void*)
(For compiler MSVC)
To make you understand better, let's change the program a bit
#include<iostream>
using namespace std;
int main(void)
{
unsigned long long x, y; // x e y son enteros sin signo de 64-bit
int i;
i = 10;
x = (unsigned long long) &i; // x es igual a la dirección en memoria de i
y = x; // y es igual a x (y por ende a la dirección en memoria de i)
*((int*)x) = *((int*)y) + 1; // se reinterpretan las dirección contenidas por x e y
// como direcciones a enteros, y se desreferencian
cout << i << endl;
*((int*)y) = *((int*)x) + 1; // lo mismo que el comentario de arriba
cout << i << endl;
return 0;
}
In C ++ the type checking is not very flexible compared to the type checking of C, so unfortunately you have to do explicit casting of a type void*
to unsigned long long
The previous program is totally equivalent to the following:
#include<iostream>
using namespace std;
int main(void)
{
void *x, *y; // x e y son punteros
int i;
i = 10;
x = &i; // x es igual a la dirección en memoria de i
y = x; // y es igual a x (y por ende a la dirección en memoria de i)
*((int*)x) = *((int*)y) + 1; // se reinterpretan las dirección contenidas por x e y
// como direcciones a enteros, y se desreferencian
cout << i << endl;
*((int*)y) = *((int*)x) + 1; // lo mismo que el comentario de arriba
cout << i << endl;
return 0;
}
Now the million question is: If x and y are pointers why do I need to cast them to int*
. Actually the casting is due to the fact that the compiler must go to the memory to which the variable points and extract a certain number of bytes from it.
At the time of wanting to access the memory pointed by a pointer of type void*
, the size of the area to be extracted must be specified. The compiler is quite intelligent, if you declare a pointer as int*
it knows that it should go and extract sizeof(int)
bytes to the address contained in i
and treat the extracted memory as objects of type int
. However this has nothing to do with pointers, the pointers are simply integers. Having different types of pointers is simply to help the compiler in his arduous task of transforming source code into machine code.