+ 2

Don't understand the answer

The question of the challenge was : "What is the output of this code ? int x = 3; int *y = 4; y = &x; cout << *y;" The answer is "error". I don't see the line which cause the error, even if the line 2 is ambiguous because it assign to y the address 4 (if I understand well). Why this code output an error ? Thanks for constructive answers.

30th Sep 2020, 8:09 AM
#D.D.
3 odpowiedzi
+ 3
It is because of line "int *y = 4;". It is invalid conversion from int to int*. A value cannot be assigned to a pointer this way. It doesn't assign to y addres 4 as you thought. To take an adress of something, operator & have to be used. Pointers are little tricky, so when you finish the challenge and if you are not sure about the answer, write that code and run it. It is the best way to see what happens and what is the mistake, then try to correct it, play with codes.
30th Sep 2020, 8:24 AM
xxxx
+ 2
Problem is a memory - int *y = 4; Pointer (*) It's a dynamic memory Do it like this int x = 3; int *y = new int(4); y = &x; cout << *y;
30th Sep 2020, 8:43 AM
BEKZATKAZ
BEKZATKAZ - avatar