0
Should a pointer have same data type as the variable to which it points to?
5 Respuestas
+ 1
yes of course
0
Pointers of any type store memory addresses. The difference between pointers with different types is not related to their addressing method or address structure.
~example~
int a = 10;
double b = 20.5;
int *ap = &a;
double *bp = &b;
address of ap is 0x10fff870 and address of bp is 0x10fff878, for example. They have the same hexadecimal arrangment with specific offset based on the size of int or double
~reason why~
The reason why we use different pointer types is the matter of accessing (dereferencing) to or modifying the pointed value for which we defined the pointer. (like normal variables, pointers are strongly typed, as well)
~example~
The following is a compilation error because int pointer cannot convert to char pointer
int n = 513;
char *np = &n;
Although you can force the compiler to squeez the int into char but with some serious data loss.
char *np = reinterpret_cast<char *>(&n);
Now, by dereferencing the np the result would be 1 instead of 513 (in little endian machines*).
0
______
* The right most byte of the binary sequence fits into a char type which is 1
513
00000000 00000000 00000010 00000001
However, individual bytes of the sequence will be accessable as
*np = 1
*(np+1) = 2
*(np+2) = 0
*(np+3) = 0