我刚刚读到我们需要在 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.
这篇关于声明类型的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
std::reference_wrapper 和简单指针的区别?Difference between std::reference_wrapper and simple pointer?(std::reference_wrapper 和简单指针的区别?)
常量之间的区别.指针和引用?Difference between const. pointer and reference?(常量之间的区别.指针和引用?)
c++ - 如何从指向向量的指针访问向量的内容?How to access the contents of a vector from a pointer to the vector in C++?(c++ - 如何从指向向量的指针访问向量的内容?)
*& 的含义和**&在 C++ 中Meaning of *amp; and **amp; in C++(*amp; 的含义和**amp;在 C++ 中)
为什么我不能对普通变量进行多态?Why can#39;t I do polymorphism with normal variables?(为什么我不能对普通变量进行多态?)
取消引用已删除的指针总是会导致访问冲突?Dereferencing deleted pointers always result in an Access Violation?(取消引用已删除的指针总是会导致访问冲突?)