【问题标题】:a question about the parameter in this function关于这个函数中参数的问题
【发布时间】:2019-09-29 06:53:14
【问题描述】:

我对以下代码有两个问题,尤其是int sum(const int *begin, const int *end) 函数。我不明白的是,那个函数中的*pp 是什么?

*p 是该函数中的指针吗?p 呢? p 是变量吗?我读到的是:“const int *p 中,*p(指向的内容)是恒定的,但p 不是恒定的。

我不太明白这个函数中*pp 的区别。

我的第二个问题是:在int sum(...)的for循环中声明const在:const int *p = begin的原因是什么?是不是因为在int sum(...) 的签名中,有这个const 被声明为:const int *p = begin? IE。是不是因为 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;
}

【问题讨论】:

    标签: c++ pointers constants


    【解决方案1】:

    p 是一个指针变量。 *有两层含义:

    1. 是指针声明
    2. 它的运算符应用于p 变量以获取其值
    const int* p; // (1) p is pointer on immutable int
    int x = *p; // (2) let's take value where p points and put it in x
    *p = 1; // (2) set value where p points
    

    是的,你对 p 的 const 是正确的。这是因为beginconst

    【讨论】:

    • 我还要提一下:指针意味着存储某物的地址。在声明中,* 之前的类型表示“某物”的类型。
    • 由于指针只是一个地址,地址实际代表什么并不明确也不相关。这可能是由newnew[] 分配的全局变量、局部变量或内存。实际上,无论地址的存储是如何提供的,指针都允许访问内存。
    • 您好,感谢您的回答。但我想我的问题是为什么我们将 p 分配为指向不可变常量的指针,即开始。但是我们在 int sum() 的 for 循环中也有 ++p?为什么是 ++p 而不是 ++p*?为什么是 p!=end 而不是 *p!= end?
    • ++p 会影响 p 指向的位置吗?即 ++p 是否也从 1 开始增加?我想这不是因为 p 被声明为指向不可变“开始”的指针。但我不明白 for 循环条件内的第二个条目和第三个条目。我不明白 ++p 和 p!= 0。
    • p 是内存中 int 的指针。 p + 1 它是内存中下一个 int 的指针。尝试阅读一些关于 C/C++ 中指针及其算法的文章。例如this
    猜你喜欢
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多