首页 > 解决方案 > 关于 *p 和 for 循环中的 p 的问题

问题描述

我对以下代码有两个问题,特别是int sum(const int *begin, const int *end)函数。我不明白的是为什么我们将它分配p为指向不可变常量的指针,即开始。但是接下来我们也有++pfor循环里面sum()吗?为什么它是++p但不是++*p?为什么它是p!=end但不是*p!= end

我读到的是:“const int *p*p(指向的内容)是恒定的,但p不是恒定的。

我不太明白这个函数的用法*p和用法之间的区别。p

我的第二个问题是:在 for 循环中声明constin: 的原因是什么?是不是因为在 的签名中,有这个被声明为: ?即是因为被声明为不可变的东西 - 所以这就是为什么在 for 循环中,我们必须声明是指针指向的不可变常量?const int *p = beginint sum(...)int sum(...)constconst int *p = beginbeginbegin*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;
}

标签: c++pointersconstants

解决方案


提醒一下,表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:递增指针
让我们分配一个指针p0x12 的值。
整数长度为 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 字节边界对齐


推荐阅读