简体   繁体   English

C ++数组和指针

[英]C++ arrays and pointers

I was wondering if someone could clear this up for me. 我想知道是否有人可以帮我解决这个问题。 It concerns pointers and arrays. 它涉及指针和数组。

double wages[3] = {10000.0, 20000.0, 30000.0};
double * pw = wages;

In the above example one can access an element in the array the following two ways: 在上面的示例中,可以通过以下两种方式访问​​数组中的元素:

wages[1] or 
*(wages+ 1)

Then I stumbled upon another piece of code: 然后我偶然发现了另一段代码:

void fill(std::array<double, Seasons> * pa)
{   
    using namespace std;
    for (int i = 0; i < Seasons; i++)
    {
        cout << "Enter " << Snames[i] << " expenses: ";
        cin >> (*pa)[i];
    }
}

Why can't we write pa[i] since pa is a pointer. 为什么我们不能写pa[i]因为pa是一个指针。 Isn't it the same as the example above? 与上面的示例不一样吗?

pa is a pointer to an object, the type of which is std::array<double, Seasons> . pa是指向对象的指针,其类型为std::array<double, Seasons>

pa[i] will not get you the i'th double in the std::array , it will attempt to access another std::array in memory that wasn't allocated for it, and will result in undefined behavior. pa[i]不会使您在std::array获得第i个double,它将尝试访问未为其分配的内存中的另一个std::array ,并且将导致未定义的行为。

(*pa) results in a reference to a std::array object, which implements operator[] . (*pa)导致对std::array对象的引用,该对象实现operator[]
(*pa)[i] calls operator[] of std::array on the aforementioned object. (*pa)[i]调用上述对象上std::array operator[]

Why can't we write pa[i] since pa is a pointer. 为什么我们不能写pa [i],因为pa是一个指针。

pa is pointer to array. pa是指向数组的指针。 So pa[i] does not dereference the i th element of the current array as you would expect - that syntax works as if pa is array of pointers instead. 因此, pa[i]不会像您期望的那样取消对当前数组的第i个元素的引用-该语法的工作方式就像pa是指针数组一样。

(*pa)[i] dereference the i th element of the array pointed by pa . (*pa)[i]取消引用pa指向的数组的第i个元素。

您也可以使用pa-> at(i)而不是pa.at(i)来访问该元素,因为pa是指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM