Yes, you are right. we can store the value in a pointer in a general int (only if sizeof(int*)==sizeof(int)) or a long
I tried this piece of code
1 2 3 4 5 6 7
|
#include<iostream>
void main()
{
int a=10,b,*p=&a;
b=int(p);
std::cout<<b<<std::endl;
}
| |
It works without any error.
But there is a reason why we use pointers:
1. You can dereference a typed pointer.
2. If you store addresses in ints, you will always have to use type casts for changing its value to store the address of another variable.
3. Using pointers introduce type safety.
4. It enables you to overload functions taking pointers as arguments.
For eg, 'int func(char*)', 'int func(int*)' and 'int func(char**)' can be 3 overloads of 'func'.
This wouldn't be possible if all pointers would be considered the same.
Basically, using an int to store an address is worse than using void* everywhere.