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;
p2to the second element, you can replacep2 = a+1;withp2 = p2+1;or simply++p2;*(p2+0) = x;and*(p2+1) = x;.