Quote:Original post by AnonymousTipster
Thanks for your help everyone, it seems I need to learn the difference between pointers and references.
References are the object, pointers store the address of the object (or at least, this is how it should be thought of).
#include <iostream>void incrementUsingReference(int &value){ // Using a reference means we can use value as if it were the variable itself value++;}void incrementUsingPointer(int *value){ // Dereferences pointer and increments the value stored at the address (*value)++;}void incrementPointer(int *value){ // No effect - increments the local pointer to the next address value++;}int main(){ int test = 0; incrementUsingReference(test); std::cout << test << std::endl; // "1" incrementUsingPointer(&test); // We have to take the address of test, too... std::cout << test << std::endl; // "2" // Since the function's broken it doesn't matter if we take the address incrementUsingPointer(&test); std::cout << test << std::endl; // "2" // Demonstration: incrementPointer(test); // Access exception! Invalid pointer used.}
Quote:Out of curiosity, would my original code work in C, GCC or otherwise, or am I being delusional?
No, it wouldn't. value has scope local to that function, because it's passed in as a parameter. When you modify it, you modify the local copy - and so no changes are made.
Quote:Quote:Original post by Zahlman's Signature
As a general rule, if you post in For Beginners and your code contains the word 'char', you have a bug. std::string roxors teh big one one one one.
Fair enough, but pointers of any size are expanded to 4byte addresses, regardless of type aren't they?
Only on 32 bit platforms. Don't rely on it.
EDIT (2/1/07): Oops, transposed two function calls in my sample code - sorry!
[Edited by - TheUnbeliever on February 2, 2007 9:00:29 AM]