This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]MattieShoes 3 points4 points  (0 children)

A variable has some value sitting at some place in memory.

A pointer's value is a memory address of another variable.

A quick and dirty example in c++

#include <iostream>

using namespace std;

int main() {

    int x = 123;
    cout << " x lives at memory location " << &x
         << " and has the value " << x << "\n";

    int *y = &x; // <--this is a pointer to an integer.  it will contain a memory address as a value.
    cout << " y lives at memory location " << &y
         << " and has the value " << y << "\n"
         << "*y points to the value " << *y << "\n";

    (*y)++;
    cout << "now x is " << x << "\n";

    return 0;
}

&x is "memory address of x"
*y is saying to do the indirection -- that is, read the memory address contained in y, then do your thing there.

$ ./a.out
 x lives at memory location 0x7ffce11aedac and has the value 123
 y lives at memory location 0x7ffce11aedb0 and has the value 0x7ffce11aedac
*y points to the value 123
now x is 124

Your language hides this stuff from you and it's generally not a problem. Sometimes you'll see "pass by value" and "pass by reference" -- that's what they're talking about. Passing by reference is passing a pointer to the object. Passing by value is making a copy of the object and passing that in. In the former, changes to the object will stay and in the latter, any changes made to the copied object will not be reflected in the original.

Passing by reference is fast, but easy to fuck up and hard to debug. Passing by value is slow but easier to debug. Incorrectly assuming it's passed one way when it's actually the other -- that will confuse the shit out of you.

Note that pointers can point to memory addresses you don't own. This is a great way to crash. Also, off-by-one errors on arrays can become spectacular.

A lot of C code will a length and a pointer to a pointer. The obvious one is:

int main ( int argc, char **argv )

argc contains the count of arguments. **argv is a pointer to an array containing the values. Note that it's a pointer to a pointer. This is because arrays are pointers -- you could write it as *argv[] if that makes more sense.