This is basically just to help me understand pointers better, so if you guys can confirm/deny/explain anything it looks like I don’t understand properly I would be most appreciative. The examples of using mailboxes, and aunts, and streets, and all that crap is just confusing.
int a = 5;
int b = &a; // b will be the memory address of 'a'
int *c = a; // c will be the value of 'a' which is 5
int *d = &a; // d will be a pointer to the memory address of 'a'
int &e = a; // what would this be?
void FunctionA()
{
int a = 20;
FunctionB(&a);
// a is now 15?
}
void FunctionB(int *a)
{
a = 15;
}
Thank you guys for any help, I am just trying to improve my understanding beyond all of the crappy metaphor explanations im reading.
I’ll take things one by one:
No. The compiler (probably) won’t allow this. You’ve defined
bto be anint, but&ais the address of anint, so the initialization won’t work.No — same problem, but in reverse. You’ve defined
cto be a pointer to anint, but you’re trying to initialize it with the value of an int.Yes — you’ve defined
dto be a pointer to an int, and you’re assigning the address of anintto it — that’s fine. The address of an int (or an array ofints) is what a pointer tointholds.This defines
eto be a reference to anintand initializes it as a reference toa. It’s perfectly legitimate, but probably not very useful. Just for Reference, the most common use of a reference is as a function parameter (though there are other purposes, of course).To make this work, you need to change the assignment in FunctionB:
As it was, you were trying to assign an
intto a pointer, which won’t work. You need to assign theintto theintthat the pointer points at to change the value in the calling function.