why the type of a pointer and object wich the pointer points must match ?
i understand what my book is trying to explain me but i have some doubt...
if the use of a pointer dereference operator get the object to which the pointer points, and I can modify the object via the pointer, why the type of the pointer must match the type to which the pointer points?
the value of a pointer confuses me a lot because I know that its value is an address but I wonder why if we just use the dereference operator on a pointer to get the object to which it points must match types?
My explanation is that when we use the dereference operator we are using the object to which the pointer points, and therefore indirectly the operations on that object must be the same operations supported by the pointer .. I am very insecure at times
So you are asking why we can't do something like this:
1 2
int value;
float* pointer = &value;
Well, if we could then *pointer would return a float. Interpreting an int as a float would probably give you a completely different value because int and floats are stored in very different ways.
You could actually test this if you convert the pointer type explicitly.
1 2 3 4 5 6 7 8
#include <iostream>
int main()
{
int value = 1;
float* pointer = reinterpret_cast<float*>(&value);
std::cout << *pointer << std::endl;
}
For me this program prints 1.4013e-45 which is a very small value and totally different from the integer value 1.
Note that doing this kind of pointer conversion (cast) is not very "safe" and you shouldn't do it in real code unless you know exactly what you are doing.