+ 3
Can you explain the 8th number line in the code?
2 Respostas
+ 2
Hi Sayan,
So, the line we are interested is "*(int*)&x=10;". Let's go by parts.
First, let me rewrite this line with some extra parenthesis:
> *((int*)(&x))=10;
You can verify that this is equivalent to the line 8;
Now, the (&x) part means we are getting the address (or reference) of variable x. The (int*) part is called casting, which means that we are forcing this reference to variable x to be of type "pointer to integer". So, together (int*)(&x) means that we are getting the reference of the "integer" variable x. In other words, it becomes a pointer to x.
As we are assigning a constant integer value (here "= 10") to the variable on the address ((int*)(&x)), we need the operator "*" to have access to the storage space at that address. So, with
*((int*)(&x)) we are dereferencing the pointer to x and putting 10 at the location.
The last part concerns the initial declaration of x as "const int x", meaning that x was a constant variable, what prevents its content from being modified. It is this the reason why "*ptrx = 10" fails. By applying the casting "(int*)" you are temporary transforming the variable "const int x" to something like "int x".
You can try to apply the casting (int*) in line 7, and it will also works. Like this: "*(int*)ptrx = 10;"
Hope I managed to explain it.
+ 1
Mark Thank you so much. I've understood now.