c++ - 关于 *p 和 for 循环中的 p 的问题
问题描述
我对以下代码有两个问题,特别是int sum(const int *begin, const int *end)
函数。我不明白的是为什么我们将它分配p
为指向不可变常量的指针,即开始。但是接下来我们也有++p
在for
循环里面sum()
吗?为什么它是++p
但不是++*p
?为什么它是p!=end
但不是*p!= end
?
我读到的是:“在const int *p
,*p
(指向的内容)是恒定的,但p
不是恒定的。 ”
我不太明白这个函数的用法*p
和用法之间的区别。p
我的第二个问题是:在 for 循环中声明const
in: 的原因是什么?是不是因为在 的签名中,有这个被声明为: ?即是因为被声明为不可变的东西 - 所以这就是为什么在 for 循环中,我们必须声明是指针指向的不可变常量?const int *p = begin
int sum(...)
int sum(...)
const
const int *p = begin
begin
begin
*p
/* Function to compute the sum of a range of an array (SumArrayRange.cpp) */
#include <iostream>
using namespace std;
// Function prototype
int sum(const int *begin, const int *end);
// Test Driver
int main() {
int a[] = {8, 4, 5, 3, 2, 1, 4, 8};
cout << sum(a, a+8) << endl; // a[0] to a[7]
cout << sum(a+2, a+5) << endl; // a[2] to a[4]
cout << sum(&a[2], &a[5]) << endl; // a[2] to a[4]
}
// Function definition
// Return the sum of the given array of the range from
// begin to end, exclude end.
int sum(const int *begin, const int *end) {
int sum = 0;
for (const int *p = begin; p != end; ++p) {
sum += *p;
}
return sum;
}
解决方案
提醒一下,表const
和指针:
int * p -- Pointer to a mutable (read/write) location. Pointer and target data may be modified.
int const * p -- Pointer to read only location. The data at the location constant, read-only.
int * const p -- Constant pointer to read/write location. Pointer can't be changed, but data at location may be changed.
int const * const p -- Constant pointer to constant data. Neither pointer nor data may be changed.
在声明中:
int sum(const int *begin, const int *end);
指针是指向常量数据的可变指针。指针可能会被修改,但它们指向常量(只读)数据。
编辑 1:递增指针
让我们分配一个指针p
0x12 的值。
整数长度为 4 个字节:
+---+
p -> | 1 | 0x12
+---+
| 2 | 0x13
+---+
| 3 | 0x14
+---+
| 4 | 0x15
+---+
| 0 | 0x16
+---+
| 6 | 0x17
+---+
| 1 | 0x18
+---+
| 9 | 0x19
+---+
== 1234处的整数*p
(提供大端布局)。
递增p
将产生地址:0x12 + 1 * sizeof(int)
或
0x12 + 1 * (4) == 0x16
。
+---+
p -> | 1 | 0x12
+---+
| 2 | 0x13
+---+
| 3 | 0x14
+---+
| 4 | 0x15
+---+
p + 1 -> | 0 | 0x16
+---+
| 6 | 0x17
+---+
| 1 | 0x18
+---+
| 9 | 0x19
+---+
编辑2:对齐在这个角度存在对齐
问题。
假设处理器是 32 位的。它有一个 32 位(4 个八位字节)大小的内部寄存器(字)。处理器被定义为从内存中取出 32 位。
让我们将整数存储在地址 4、8、12 和 16。这些地址的二进制表示:
0000 0100 -- 4
0000 1000 -- 8
0000 1100 -- 12
0001 0000 -- 16
如您所见,最右边的 2 位始终为零。处理器设计人员不需要实现最右边的 2 个地址线(从而节省资金和房地产空间)。在此处理器中,在可被 4 整除的地址处取指是最有效的(取指 1 次)。它们与 4 字节边界对齐。
推荐阅读
- javascript - 如何停止 render() 函数,直到所有状态都被更新?
- r - 用R中的伽马不完全函数计算双积分
- pimcore - Pimcore:更新到 Pimcore 4 后无法使用 Pimcore\Model\Object
- r - 如何在 R 的 emmeans 包中计算 SE
- javascript - PrimeNG FullCalendar 不工作,无法找到
- openid-connect - OIDC 登录重定向返回 500 错误 (signin-oidc)
- midi - 无法使用 music21 库在 Python 中解析 MIDI 文件
- css - 如何让 CSS 溢出和高度:计算在可调整大小的 div 中工作
- c# - 我想制作一个我自己的按钮,里面有两个其他按钮,我想让它们透明但透明度不起作用
- hyperledger-fabric - Hyperledger Fabric 中的私有数据是否适用读写原则?