指针实际上是如何按类型递增的
How are pointers actually made to increment by the type their type
如何使指针按类型递增。例如,如果我们有
int *ptr;
ptr++; //would point to the next integer i.e. it would increment ptr by 4bytes in 32 bit system
我想知道这是如何在内部完成的。
编译代码的编译器知道指针的基类型,并将代码适当地放入递增指针(偏移量)。例如:
int* p = new int[10];
*(p+2) = 100;
第二行是这样的:
p + sizeof(int) * 2 ... // Not C/C++
类似地:
p++;
意思是:
p = p + sizeof(int); // Not C/C++
如果p
的类型是其他类型(如float
或某种结构),则将适当地执行计算。没有魔法。类型是编译时定义的——一种类型的变量在运行时不会改变,因此计算也是如此。
相关文章:
- boost 是否有按特殊类型值编码状态"compact optional"?
- c++ 11 带有 decltype 的尾随返回类型无法按预期工作
- 推理类型如何工作"auto"和按引用调用?
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 如何按多个括号类型拆分字符串,但仍将括号保留在C++?
- Poco 库 PUT 方法未按预期工作,尽管主机、方法、内容类型设置正确
- 使模板函数按函数参数选择类型
- 在 std::variant 中按类型获取索引
- 外部基础类型未按请求对齐时的atomic_ref
- 我无法在用forward_as_tuple创建的元组中按类型访问元素
- 如何在 CMake 中"override"文件的按扩展名类型
- 在 C++ 中按参数创建不同类型的对象?
- 为什么"const auto [x, y]"绑定到引用类型时没有按预期运行?
- 增强序列化,按基类型加载存档类会产生错误的数据
- 对于可移动类型,按值传递比重载函数更好吗?
- 具有不同类型的按位移位表达式 1 <<表达式 2 会损害性能吗?
- C++视图类型:按常量传递还是按值传递?
- 了解 C++14 中有符号类型的按位左移
- 如果类类型是按值调用的函数的参数,则会调用该类的重载赋值运算符吗?
- 无符号类型的按位移位中的 RHS 操作数的类型