The size of pointer is same irrespective of datatype it is pointing to.Then why do we need to declare the datatype it points to?
For example,
int *p; //p will point to an integer data type.
char *p; //p will point to a character
Then,why can't we generalize a pointer declaration like this
pointer p; //where p is an object of pointer class.
TL;DR because, different data types occupy different size in memory and has different alignment requirement.
To elaborate, a pointer variable holds an address which points to some type of data. Without the type associated, there would be no way to dereference the pointer and get the value.
In other words, to access the data pointed to by a pointer, the associated data type must be known.
The size of the pointer itself, has little connection to the actual data it points to.
There exists a pointer , void *
which is considered a generic pointer, but then, you can't dereference it, as the result of dereference would attempt to produce an incomplete type. You need to cast it to a complete type to be able to dereference or apply pointer arithmetic on a void pointer.
The reason behind considering void *
a generic pointer is as below, quoting from the C11
standard, chapter §6.3.2.3
A pointer to
void
may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer tovoid
and back again; the result shall compare equal to the original pointer.
So, a void *
can be used as a generic container which can hold any pointer type, but to make some operation on the pointer (which includes the knowledge of the data type), you need to cast it to a complete type first.
You can generalize pointers using void*
. void*
is a pointer to some address without any type information associated. However, there is little you can do with these pointers without casting them to an explicit pointer type first.
Consider the following example. It will not compile, because it's impossible to deduce the "value" pointed to by ptr
is. You can't even know how many bytes constitute the value.
void print(const void * ptr) {
std::cout << *ptr; // What's the "value" of ptr?
}
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