我对以下代码有两个问题,特别是int sum(const int *begin, const int *end)
函数。我不明白的原因是为什么我们将p
分配为不可变常量(即begin)的指针。但是,在++p
内的for
循环中还有sum()
吗?为什么是++p
而不是++*p
?为什么是p!=end
而不是*p!= end
?
我正在阅读:“ 在const int *p
中,*p
(指向的内容)是常数,但是p
不是常数。”
我不太了解此功能中*p
和p
的用法之间的区别。
[我的第二个问题是:在const
的for循环中的const int *p = begin
中声明int sum(...)
的原因是什么?是因为在int sum(...)
的签名中声明了const
的const int *p = begin
吗?即是因为begin
被声明为不可变的东西-这就是为什么在for循环中,我们必须声明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
+---+
*p
处的整数== 1234(提供的Big Endian布局)。
递增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:对齐从这个角度来看,存在一个alignment问题。假设处理器为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字节边界。