+ 2

can someone explain why a,*&a and &b outputs the same address

include <iostream> using namespace std; int main(){ int *a; int b=10; a=&b; cout<<a<<endl; cout<<*a<<endl; cout<<*&a<<endl; cout<<b<<endl; cout<<&b<<endl; return 0; }

9th Dec 2022, 2:55 AM
Mahdi
Mahdi - avatar
3 Answers
+ 2
In the code you provided, the a variable is a pointer that stores the address of the b variable. When the cout statements are executed, the following values are output: a: The address of the b variable is output, because a is a pointer that stores this address. *a: The value of the b variable is output, because the * operator dereferences the pointer a and accesses the value stored at the address it points to (i.e., the value of b). *&a: The address of the b variable is output, because the & operator returns the address of a variable, and the * operator dereferences a pointer and accesses the value stored at the address it points to. In this case, *&a returns the address stored in the a pointer, which is the address of the b variable. b: The value of the b variable is output, because the b variable is not a pointer and its value is accessed directly. &b: The address of the b variable is output, because the & operator returns the address of a variable.
9th Dec 2022, 3:41 AM
CalviÕ²
CalviÕ² - avatar
+ 1
Hopefully someone with more experience can clarify better, but from what I see: You created a pointer: int *a; then gave var b a value: int b=10; then you set 'a' to point at the address of 'b' so 'a' no longer has it's own address, it is pointing at 'b's address (a = address of b): a=&b; so essentially the address of a and b are the same. calling a is the same as calling &b: cout<<a<<endl; this points to the value of b: cout<<*a<<endl; this points to the address of b since you made a=&b: cout<<*&a<<endl; this is the value of b: cout<<b<<endl; this is the address of b: cout<<&b<<endl;
9th Dec 2022, 3:26 AM
Scott D
Scott D - avatar
0
A pointer is a type of variable that stores the memory address of another variable. In this code, the pointer a is initialized to point to the memory location of the variable b, so a contains the address of b in memory. The * symbol is used to dereference a pointer, which means to access the value stored at the memory location pointed to by the pointer. Since a points to the same memory location as b, dereferencing a with *a returns the same value as the variable b. *&a also dereferences the pointer a, so it also returns the same value. Since b and &b both represent the same memory location, they both output the same address. In simpler terms, a, *&a, and &b all represent the same memory location and contain the same value, so they all output the same address.
9th Dec 2022, 4:56 AM
THATguy18
THATguy18 - avatar