Why can't we generalize the pointer declaration?

The size of the pointer is the same, regardless of the type of data it points to. Then why do we need to declare the data type that it points to?

For instance,

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.
+4
source share
6 answers

TL DR , because different data types occupy different sizes in memory and have different alignment requirements.

To clarify, a pointer variable contains an address that points to some type of data. Without a bound type, there would be no way to dereference a pointer and get a value.

, , , .

, , .

void *, , , . , void.

void * , C11, §6.3.2.3

void . void ; .

, a void * , , ( ) .

+13

.

:

int arr[] = {4, 6, 9, 10};
int* x = arr;

*(x+0) = 4
*(x+1) = 6

, x + 1 x + sizeof (int), 1.

, sizeof (int) . , .

, , . A char 1 , int 1 .

+6

, void*. void* - - . , , .

. , "", ptr. , .

void print(const void * ptr) {
    std::cout << *ptr; // What the "value" of ptr?
}
+6

A void * "" .

, , , . void * , , , .

, void *.

+2

, , .

: :

void , . 48) , . . . .

C 2011 Online Draft, & sect; 6.2.5 & para; 28

. (3.11).

++ 2014 , & sect; 3.9.2, & para; 3

, , .

, ?

- p T, p + 1 T. , "", .

+1

Then why can't we generalize a pointer declaration like this

 pointer p;  //where p is an object of pointer class.

In fact you can use void*. But the consequence of this is that all information about the type (and size) is lost at this point.

You will need to track this in some way (hardcoded to the type or something else) to make it useful.

0
source

Source: https://habr.com/ru/post/1670957/


All Articles