Pointers and references...
I'm sure this has probably been asked before.. but I didn't find it in a forum search.
What exactly is the difference between pointers and (I think references is the right term.. maybe not..) references?
Just incase I got the references term wrong, what I mean is the difference between int &x and int *x.
I understand a reference is like an alias of sorts to a variable, and a pointer can (does?) point to a place in memory, but i'm not sure what the real differences, when it comes to passing to functions, usage, etc. etc. are.
Sorry for the newbie question, but I couldn't find any straight comparisons, and it would help me grasp the usage of both alittle better.
Thanks!
pointers/references one more time
Zen, as another newbie wrestling with the same question, can you confirm what I think you said:
Here are 2 functions
1. void fn(int& n, char& c) {n=3*n;}
2. void fn(int *n, char *c) {*n=3*(*n);}
both of these will change whatever I pass as n to 3*n. Please tell me that's right.
But let me "wrestle" out loud with the rest of my problem: My Schaum's Outline makes a distinction between &/* as operators and type-modifiers which I interpret as follows:
Operator:
1. ptr = &n -- means that &n is an expression which evaluates to the address of n but leaves n unchanged.
2. n=*ptr similarly sets n to the value ptr is pointing to without changing ptr.
Type modifier:
int& n; makes n a var of refers_to_an_int type
int* n; makes n a var of point_to_an_int type
Now assuming that the designers of C/C++ are smart, there must be a reason for using the same symbol for 2 different purposes, which is hopefully, that they are not different.
Here's my shot at that:
1. addressOf operator &n outputs an address which is obviously what you must pass to a function that is going to change n. This is why your description of "int& n;" as some kind of pointer rang a bell with me. An address should be/make a pointer. And since I like meaningful names, I would have included "pointer" in its name . . . maybe refPointer, or some such monster.
2. dereference operator *ptr outputs a value whereas int* n creates a pointer. This makes no sense to me.
First of all, shouldn't it be called the depointer operator? The only guess I can make as to their thinking is that if the first * (in the declaration) creates a pointer, it makes sense that the 2nd * (operator) would UNmake a pointer.
Zen, you sound like you might be able to lead us all out of the wilderness, or at least confirm some of my suspicions.
Thanx for your response,
Al