Skip to main content
added 381 characters in body
Source Link

I assume you defined

int * p2;

Then int * p2; Then, what you mean to do is

int a[2];
p2 = a; //set pointer to address of a[0]
*p2 = x; //set value of a[0] to value of x
cout << "The address of the first element in a is: " << p2 << endl;  // (1)
p2 = a+1;
*p2 = y;
cout << "The address of the second element in a is: " << p2 << endl; // (2)

In the following table I show the contents of various expressions, at points (1) and (2)

            p2                    &p2
(1)   address of a[0]   address where p2 is stored
(2)   address of a[1]   address where p2 is stored

&p2 does not contain the address of a[0] (that is p2), but the address where that value (i.e., that address) is stored. So when you increment p2 (you could have done p2++ as well), &p2 does not change. The fact that p2 is a pointer and you mean to use it to traverse array elements may lead to confusion, but it is irrelevant.

I assume you defined

int * p2;

Then, what you mean to do is

int a[2];
p2 = a; //set pointer to address of a[0]
*p2 = x; //set value of a[0] to value of x
cout << "The address of the first element in a is: " << p2 << endl;
p2 = a+1;
*p2 = y;
cout << "The address of the second element in a is: " << p2 << endl;

&p2 does not contain the address of a[0] (that is p2), but the address where that value (i.e., that address) is stored. So when you increment p2 (you could have done p2++ as well), &p2 does not change.

I assume you defined int * p2; Then, what you mean to do is

int a[2];
p2 = a; //set pointer to address of a[0]
*p2 = x; //set value of a[0] to value of x
cout << "The address of the first element in a is: " << p2 << endl;  // (1)
p2 = a+1;
*p2 = y;
cout << "The address of the second element in a is: " << p2 << endl; // (2)

In the following table I show the contents of various expressions, at points (1) and (2)

            p2                    &p2
(1)   address of a[0]   address where p2 is stored
(2)   address of a[1]   address where p2 is stored

&p2 does not contain the address of a[0] (that is p2), but the address where that value (i.e., that address) is stored. So when you increment p2 (you could have done p2++ as well), &p2 does not change. The fact that p2 is a pointer and you mean to use it to traverse array elements may lead to confusion, but it is irrelevant.

Source Link

I assume you defined

int * p2;

Then, what you mean to do is

int a[2];
p2 = a; //set pointer to address of a[0]
*p2 = x; //set value of a[0] to value of x
cout << "The address of the first element in a is: " << p2 << endl;
p2 = a+1;
*p2 = y;
cout << "The address of the second element in a is: " << p2 << endl;

&p2 does not contain the address of a[0] (that is p2), but the address where that value (i.e., that address) is stored. So when you increment p2 (you could have done p2++ as well), &p2 does not change.