Pointers

I have the following questions:
For parts b-e, repeat the declaration and use the results from a.



int x = 6, y = 5, *px, *py;

a) Write 2 assignment statements that set px and py to point at integers x and y. (I think it is *px = &x, *py = &y

b) Write an output statement using px that print the contents of x. (I have cout << *px << endl

c) Write a statement using py that assigns 20 as the contents of y. (I have *py *=4

d) What is the resulting value of *py + *px? (Would it not be simply 11 using the results from part a)

e) After executing *py = *px, are &x and *py equal? (I say yes. py now equals what px was pointing to which was &x)

I am learning all of this online and just want to make sure that I am doing this right. Thanks

BTW, I tried running this on my compiler but to no avail.
a) px = &x; py = &y;

No need for the asterisks before the pointers in this case.
Last edited on
e) After executing *py = *px, are &x and *py equal? (I say yes. py now equals what px was pointing to which was &x)

No.
e) After executing *py = *px, are &x and *py equal? (I say yes. py now equals what px was pointing to which was &x)

No.


Oh, yes, I missed that one.

The reason is that you're dereferencing py, which is y, then assigning it to the dereference of px (x). Now y and x are equal, but the question does not ask that, it asks if the dereference of py (y) is equal to the address of x. Chances are that the address of x is not equal to the value of y.
Topic archived. No new replies allowed.