+ 1

Why typecasting is needed while dereferencing a void pointer ?

15th Jul 2019, 2:35 AM
Krishna Kumar
Krishna Kumar - avatar
2 Réponses
+ 2
A normal pointer of a type known by the compiler can be incremented or decremented easily. For example, if you have memory cells like this 0xfee01 | 00000000 0xfee02 | 00000000 0xfee03 | 00000000 0xfee04 | 00000101 0xfee05 | 00000000 Then an integer which is given the address 0xfee01 will occupy the cells 0xfee01 to 0xfee04 as it requires 4 bytes. Now a pointer if pointing to this integer will store the address as 0xfee01. Now if we increment the pointer, we reach the address 0xfee05 ad not 0xfee02, as 4 bytes are part of the same int, and accessing 0xfee02 as an int will lead to corrupted data. Now if this pointer was of type char*, then increment will give us the address 0xfee02 as a char is 1 byte. So to access the value or increment or decrement pointers, the size of the type pointed to must be known. But in a void pointer, the type is not known. So it can be treated as an int*, char* or any other pointer. But to use it we will have to cast it to a type, so that the required bytes can be accessed.
15th Jul 2019, 3:27 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
15th Jul 2019, 4:31 AM
Krishna Kumar
Krishna Kumar - avatar