+ 3

Pointer dilemma

int a = 1; int b = 2; int *p = &a; *p = b; std::cout << a; // ----> prints 2 Why does a's value change this way and not change when you write "p = &b"? (*p = b, apparently changes the value of pointers pointing to a, as well...)

23rd May 2018, 5:42 PM
Zuke
Zuke - avatar
7 Respuestas
+ 5
When you do p = &b; You are storing the address of variable b in pointer p. This does not change the value of variable a. *p = b; You are storing the value of variable b into the variable which is pointed by pointer p. At this point, pointer p stores the address of variable a. Hence, the value of variable b is assigned to variable a. Try looking into the difference between the * operator and the & operator. https://code.sololearn.com/c7mW3DQoz3m0/?ref=app
24th May 2018, 2:56 AM
Hatsy Rei
Hatsy Rei - avatar
+ 6
Zuke I made the same observations. The instructions were executed in the sandbox environment consecutively, so it's likely that the memory allocation on the stack was also contiguous. I'm not aware of any standard which guarantees this, though.
24th May 2018, 5:53 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
i dont know exactly.. but i think at the time of initialization of pointer(int *p=&a;) pointer has address of a and point to a.. but when we try to store value of b not point to b its change value of a rather than again point to b.. that's why output is 2..
23rd May 2018, 5:54 PM
Scooby
Scooby - avatar
+ 2
Ohhh, thank you! Just one question, for me the pointer's address was 2 less than the string's, is that a coincidence or....?
24th May 2018, 5:49 AM
Zuke
Zuke - avatar
+ 2
Maybe the 2 is because every string has a null character at the beginning? So in memory it might look like: (pointer -> null -> char1 -> char2 -> ...)
24th May 2018, 9:54 AM
Zuke
Zuke - avatar
+ 1
Probably but this behavior is compiler dependent since the compiler decides in which order the variables are put on the stack and will reorder them if necessary for security purposes the null character is at the end by the way so it’s more like null char2 char1 char0
24th May 2018, 11:06 AM
Max
Max - avatar
0
o'zbek tilida darslar mavjudmi tashkil qiliw mumkinmi? Bu dasturda bizda qiziqishlar katta
28th May 2018, 5:46 AM
To'xtamurod Jo'rayev
To'xtamurod Jo'rayev - avatar