+ 1

Why is it important for a pointer to have the same data type as of the variable it is pointing to?

18th Sep 2018, 8:40 AM
Rahul Raghuwanshi
Rahul Raghuwanshi - avatar
2 Antworten
+ 6
Using the increasement operator operator (++) moves the pointer to the next element. If the pointer type is unknown (void) then the compiler doesn't​ know the size, so doesn't know how many bytes to move. If the pointer is the wrong type, then the compiler might use the wrong size. Same issues with any other pointer arithmetic. Also if you copy a value to the address of the pointer, the correct size is needed. *p = 2; Does this copy the 8 bit int representation into 1 byte. Or 16 bit int representation into 2 two bytes, etc. It depends on the pointer​ type. And then you will break the implicit casting. If you copy an int value to the address of a pointer to int, it will be copied as an int. If the pointer really points to floating​ point memory, then when accessed through the float variable the value will likely be meaningless, even if the int and float type are the same size.
18th Sep 2018, 10:12 AM
Jared Bird
Jared Bird - avatar
0
because yes
18th Sep 2018, 10:32 AM
Leo123 Naxus
Leo123 Naxus - avatar