Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we generalize the pointer declaration?

Tags:

c++

c

pointers

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.
like image 281
yondu_udanta Avatar asked Nov 27 '22 13:11

yondu_udanta


2 Answers

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 to void 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.

like image 73
Sourav Ghosh Avatar answered Dec 07 '22 23:12

Sourav Ghosh


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?
}
like image 41
François Andrieux Avatar answered Dec 07 '22 23:12

François Andrieux