无论指针指向的数据类型如何,指针的大小都是相同的。那为什么我们需要声明它指向的数据类型呢?
例如,
int *p; //p will point to an integer data type.
char *p; //p will point to a character
那么,为什么我们不能泛化这样的指针声明
pointer p; //where p is an object of pointer class.
最佳答案
TL;DR 因为,不同的数据类型在内存中占用的大小不同,对齐要求也不同。
详细来说,指针变量保存指向某种类型数据的地址。如果没有关联的类型,将无法取消引用指针并获取值。
换句话说,要访问指针指向的数据,必须知道关联的数据类型。
指针本身的大小,与它指向的实际数据关系不大。
存在一个指针,void *
,它被认为是一个通用指针,但是您不能取消引用它,因为取消引用的结果会尝试生成不完整的类型。您需要将其强制转换为完整类型,以便能够取消引用或在 void 指针上应用指针算法。
将void *
视为通用 指针的原因如下,引用自C11
标准,章节§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.
因此,void *
可以用作通用容器,它可以容纳任何指针类型,但可以对指针进行一些操作(包括数据类型),您需要先将其转换为完整类型。
关于c++ - 为什么我们不能泛化指针声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42492332/