Samu
Samu

Reputation: 101

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. Isn't it the same as the example above?

Upvotes: 0

Views: 79

Answers (3)

Andreea S
Andreea S

Reputation: 1

You can also access that element using pa->at(i) instead of pa.at(i) as pa is a pointer.

Upvotes: 0

tdao
tdao

Reputation: 17678

Why can't we write pa[i] since pa is a pointer.

pa is pointer to array. So pa[i] does not dereference the ith element of the current array as you would expect - that syntax works as if pa is array of pointers instead.

(*pa)[i] dereference the ith element of the array pointed by pa.

Upvotes: 0

pa is a pointer to an object, the type of which is 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) results in a reference to a std::array object, which implements operator[].
(*pa)[i] calls operator[] of std::array on the aforementioned object.

Upvotes: 3

Related Questions