声明类型的指针?

2021-12-13 00:00:00 pointers c c++

我刚刚读到我们需要在 C(或 C++)中声明指针时给出指针的类型,即:

I just read that we need to give the type of pointers while declaring them in C (or C++) i.e.:

int *point ;

据我所知,指针存储变量的地址,无论类型如何,地址都占用相同数量的内存.那么,为什么我们需要声明它的类型?

As far as I know, pointers store the address of variables, and address occupies same amount of memory whatever may be the type. So, why do we need to declare its type?

推荐答案

类型安全.如果你不知道 p 应该指向什么,那么就没有什么可以防止像

Type-safety. If you don't know what p is supposed to point to, then there'd be nothing to prevent category errors like

*p = "Nonsense";
int i = *p;

静态类型检查是防止此类错误的非常强大的工具.

Static type checking is a very powerful tool for preventing all kinds of errors like that.

C 和 C++ 还支持指针运算,它仅在目标类型的大小已知时才有效.

C and C++ also support pointer arithmetic, which only works if the size of the target type is known.

地址占用相同数量的内存,无论我是什么类型

address occupies same amount of memory whatever my be the type

对于当今流行的平台来说确实如此.但有些平台并非如此.例如,指向多字节字的指针可能比指向单字节的指针小,因为它不需要表示字在字内的偏移量.

That's true for today's popular platforms. But there have been platforms for which that wasn't the case. For example, a pointer to a multi-byte word could be smaller than a pointer to a single byte, since it doesn't need to represent the byte's offset within the word.

相关文章