0

Hi all I have an exam that involves c++ coming up and I am just struggling on pointers a little, can anyone assist,

this is an example question

What will be printed out on execution and p starts with address 0x00C0

float p = 11.0; 
p = p + 2.0;

float *q = &p; 
float *r = q; 
*r = *r + 1; 

int *s = new int(); 
*s = *q; 
*q = (*q)*10.0; 

*r = 15.0;

cout << p <<endl;
cout << *q <<endl;
cout << r <<endl;
cout << *s <<endl;
cout << *r <<endl;

now I compiled and ran this program but I cant get my head around the values of *q which = 15. Does it not get multiplied by 10?

Also r is an address in memory can anyone explain that to me please?

Help appriciated!

user2904478
  • 27
  • 1
  • 4

1 Answers1

1

Always try to think in terms of variable value instead of pointer value. If multiple pointers point to the same memory location then printing the value of the pointer (*ptr) will always give same output for all pointers.

float p = 11.0; 
p = p + 2.0;//p = 13

float *q = &p; 
float *r = q; 
*r = *r + 1;//p = 14 

int *s = new int(); 
*s = *q;//*s = 14 
*q = (*q)*10.0;//p = 140 

*r = 15.0;//p = 15//somehow did not see this line :P

cout << p <<endl;//15
cout << *q <<endl;//15
cout << r <<endl;//0x00C0
cout << *s <<endl;//14
cout << *r <<endl;//15

Proof here.

Cool_Coder
  • 4,888
  • 16
  • 57
  • 99
  • hint: float* r = q; Do something with it. – David Szalai Jan 19 '14 at 14:24
  • I mean at the end of the code *r=15 also changes q, since points to the same as q. – David Szalai Jan 19 '14 at 14:29
  • 1
    Thank you all for your help! also thank you Cool_Coder for stepping down line by line this helps alot – user2904478 Jan 19 '14 at 14:32
  • @unxnut Correct me, if I am wrong, but doesn't `float *r = q` initialize the pointer `r` with the pointer `q` (which in turn is initialized with `&p`, wherefore `r == &p` and not `*r == &p`, which in turn means that `*r = *r + 1` is the same as `p = p + 1` (so `*r` changes from `13` to `14`) not `*r = &p +1`? – Lmis Jan 19 '14 at 14:49
  • float *r = q; makes r point at the same memory location as q. Think it like this. So it doesnt make a difference if you use *r or *q because both point to the same memory location. – Cool_Coder Jan 19 '14 at 14:52
  • @Cool_Coder Yes ofc, my issue is with the comment by unxnut which includes (what I understand to be) the claim, that at some point `*r == &p`, whereas I claim `*r == p` and `r == &p` – Lmis Jan 19 '14 at 14:57
  • @Lmis, my bad. You are right that `float *r = q` assigns the address of `q` to `r`. – unxnut Jan 19 '14 at 15:08