#include <iostream>
int main() {
using namespace std;
double wages[3] = { 10000.0, 20000.0, 30000.0 };
double* pw = wages;
cout << "pw = " << pw << ", *pw = " << *pw << endl;
pw = pw + 1;
cout << "pw + 1 = " << pw << ", *(pw + 1) = " << *pw << endl;
cout << "wages + 1 = " << wages + 1 << ", *(wages + 1) = " << *(wages + 1) << endl;
//wages = wages + 1; // invalid, because wages is a const pointer
cout << "wages = " << wages << ", *wages = " << *wages << endl;
return 0;
}
Yes, in C++, the name of an array is essentially a constant pointer to the first element of the array. This means that while the contents of the array can be modified, the pointer itself (i.e., the address it holds) cannot be changed.
This is why the line wages = wages + 1;
is commented out in your code and noted as invalid. If you try to compile this line, you would get a compilation error because you're trying to change the address that wages
points to, which is not allowed.
However, you can create a separate pointer variable and assign it the address of the array (or the address of the first element of the array), and then you can increment or decrement that pointer variable. This is what's happening with the pw
pointer in your code.
Here's the relevant part of your code:
double* pw = wages; // pw is a pointer to the first element of wages
cout << "pw = " << pw << ", *pw = " << *pw << endl;
pw = pw + 1; // incrementing pw is allowed
cout << "pw + 1 = " << pw << ", *(pw + 1) = " << *pw << endl;
In this code, pw
is a pointer that initially points to the first element of the wages
array. The line pw = pw + 1;
increments the pointer to point to the next element in the array. This is allowed because pw
is a separate pointer variable, not the array name itself.