Reputation: 26868
int x = 4;
int* q = &x; // Is it always equivalent to int *q = &x; ?
cout << "q = " << q << endl; // output: q = 0xbfdded70
int i = *q; // A
int j = *(int*)q; // B, when is this necessary?
cout << "i = " << i << endl; // output: i = 4
cout << "j = " << j << endl; // output: j = 4
My question is what does lines A and B do, and why the outputs are both 4?
Upvotes: 1
Views: 136
Reputation: 49976
It is a basic usage of pointers, in A you dereference pointer (access the variable to which a pointer points)":
int i = *q; // A
while B is doing exactly the same but it additionally casts pointer to the same type. You could write it like that:
int j = *q; // B
there is no need for (int*)
Upvotes: 3
Reputation: 13356
Line A de-reference pointer q
typed as int *
, i.e. a pointer points to an int
value.
Line B cast q
as (int *)
before de-reference, so line B is the same as int j = *q;
.
Upvotes: 0
Reputation: 63735
int x = 4;
x is 4
int* q = &x;
q is the memory location of x (which holds 4)
cout << "q = " << q << endl; // output: q = 0xbfdded70
There's your memory location.
int i = *q; // A
i is the value at memory location q
int j = *(int*)q; // B
j is the value at memory location q. q is being cast to an int pointer, but that's what it already is.
Upvotes: 2
Reputation: 370112
Line A takes the value that q
points to and assigns it to i
. Line b casts q
to the type int*
(which is q
's type already, so that cast is entirely redundant/pointless), then takes the value that q points to and assigns it to j
.
Both give you 4 because that's the value that q
points to.
Upvotes: 0
Reputation: 2485
A: Dereference - takes a pointer to a value (variable or object) and returns the value
B: Cast to int*
and than dereference
The result is the same because the pointer is already to int. That's it.
Upvotes: 1
Reputation: 70931
Lines A and B are equivelent as q is already an int* and therefor (int*)q equals q. int i = *q; yelds that i becomes the value of the integer pointed to by q. If you want to make i to be equal to the adress itself remove the asterisk.
Upvotes: 1
Reputation: 206508
int i = *q; // A
Dereferences a pointer to get the pointed value
int j = *(int*)q; // B
type casts the pointer to an int *
and then dereferences it.
Both are same because the pointer is already pointing to an int. So typecasting to int *
in second case is not needed at all.
Further derefenecing yields the pointed integer variable value in both cases.
Upvotes: 1