声明类型的指针?

Declaring type of pointers?(声明类型的指针?)
本文介绍了声明类型的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我刚刚读到我们需要在 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.

这篇关于声明类型的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Could I ever want to access the address zero?(我可以想访问地址零吗?)
C++ Access derived class member from base class pointer(C++ 从基类指针访问派生类成员)
Weird Behaviour with const_cast(const_cast 的奇怪行为)
Are pointer variables just integers with some operators or are they quot;symbolicquot;?(指针变量只是带有某些运算符的整数还是“符号?)
Modifying a char *const string(修改 char *const 字符串)
Modifying a const int in C++(修改 C++ 中的 const int)