As far as I know about data types in C/C++, while declaring a variable, we need to declare its data type, which tells the compiler to reserve the number of bytes in the memory accordingly.
But in the case of pointers, we know that their size is constant (eg. 2 bytes in "Turbo Compiler"), irrespective of the data type of the variable it is pointing to, because the pointer is storing a memory address as an unsigned integer.
My question is, if the pointers are always a constant size in bytes, then what is the need of mentioning the data type while declaring them? Is my understanding about pointers wrong?
The data type of pointer is needed when dereferencing the pointer so it knows how much data it should read. For example, dereferencing a char pointer should read the next byte from the address it is pointing to, while an integer pointer should read 4 bytes.
A pointer declaration names a pointer variable and specifies the type of the object to which the variable points. A variable declared as a pointer holds a memory address.
A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory items. Pointers are very useful for another type of parameter passing, usually referred to as Pass By Address. Pointers are essential for dynamic memory allocation.
Why is it important for a pointer to have the same data type as of the variable it is pointing to? 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.
The data type is needed when dereferencing the pointer so it knows how much data it should read. For example dereferencing a char
pointer should read the next byte from the address it is pointing to while an int
pointer should read 2 bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With