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.
这篇关于声明类型的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:声明类型的指针?
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07