1

How do I go about using only one pointer, p2, to initialize values of an array of 2 elements?

I know that the array name, a, is a pointer pointing to the address of the first element in the array so I did this:

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;

Now my problem comes with trying to use the same pointer to initialize the second element in a to the value of y. Here is what I've tried:

p2 = a+1;
*p2 = y;
cout << "The address of the second element in a is: " << &p2 << endl;

When I print out the address of both elements, they come out with the same address but they should be different since they are at different addresses with different values. Any help is appreciated. Thanks.

Edit: Thank you for your responses everyone. They were very helpful. This is what I ended up doing:

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

3
  • 3
    You're printing the address of the pointer itself, not the address of what the pointer points to. Commented Mar 13, 2019 at 1:30
  • FYI, to advance p2 to the second element, you can replace p2 = a+1; with p2 = p2+1; or simply ++p2; Commented Mar 13, 2019 at 1:36
  • Instead of moving p2, try *(p2+0) = x; and *(p2+1) = x;. Commented Mar 13, 2019 at 1:50

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.