Hey guys I'm on the pointers section of C++ and I understand that & is a reference operator. so if you had a and b and you said a=&b that would be saying that a actually equals b's memory block, not just its value. But dereference operators (*) just doint make any sense. It says that it points to the value of something. so if *b=a wouldnt that just be the same as b=a? because b=a is referring to the value also.
and you said a=&b that would be saying that a actually equals b's memory block, not just its value.
No, not at all. It assigns the address of b to the pointer variable a.
so if *b=a wouldnt that just be the same as b=a?
No. Besides that it won't compile, b is a variable that that can only hold addresses to int objects (assuming a is an integer), while a is a variable that can hold only integers. So you can't do b=a;
However, when dereferencing b, you get a reference to the integer object b points to. You can assign an integer to an integer just fine, so *b=a; is okay.
Okay for the reference you said it assigns a to the address of b. What exactly does that entail? Also can you explain what it means to point to? correct me if I'm wrong but lets say a=&b. a would just be using b's same address without taking up any extra memory and a would be pointing to the address of b? and as for dereference operators I cant quite grasp the concept. Ive read the section on them a few times but could you explain them to me? I really appreciate it.
And perhaps this link to understand memory addresses better: http://www.tenouk.com/Module8.html
There might be better explanations, most books cover it too.
In the operation *a = &b , the address of 'b' is assigned to the pointer variable a i.e. 'a' points to 'b'. For e.g the variable 'b' is stored at some memory location (say 0x0000f), then &b would return the address where 'b' is stored in the memory.
Also pointer variable are used to store address of variables, i.e values like 0x0000f which represent addresses. Hence *a = &b; will assign the address of 'b' to pointer variable 'a' . Hence if we want to refer 'b' we can also use 'a', hence we say that 'a' is pointing towards 'b';
Consider this program;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
int main()
{
int *a;
int b = 7;
a = &b;
std::cout<<"Value of b : "<<b;
std::cout<<" Address of b : "<<&b;
std::cout<<" Address that a holds : "<<a;
std::cout<<" Value that a points to : "<<*a;
std::cin.get();
return 0;
} // end of main
Wow greatest feeling ever it all just clicked. though you declared variable a as a pointer then on line 7 you used a without the asterisk. Does it matter whether you use it or not?
Oh okay I just read it again. you declared that a= the address of b so when you output a alone it is simply b's address. Though when you use the asterisk it outputs the value of the address. correct me if Im wrong