Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To declare a function that takes a pointer to an int:</p> <p><code>void Foo(int *x);</code></p> <p>To use this function:</p> <pre><code> int x = 4; int *x_ptr = &x; Foo(x_ptr); Foo(&x); </code></pre> <p>If you want a pointer for another type of object, it's much the same:</p> <p><code>void Foo(Object *o);</code></p> <p>But, you may prefer to use references. They are somewhat less confusing than pointers:</p> <pre><code> // pass a reference void Foo(int &x) { x = 2; } //pass a pointer void Foo_p(int *p) { *x = 9; } // pass by value void Bar(int x) { x = 7; } int x = 4; Foo(x); // x now equals 2. Foo_p(&x); // x now equals 9. Bar(x); // x still equals 9. </code></pre> <p>With references, you still get to change the x that was passed to the function (as you would with a pointer), but you don't have to worry about dereferencing or address of operations.</p> <p>As recommended by others, check out the <a href="http://www.parashift.com/c++-faq-lite/" rel="noreferrer">C++FAQLite</a>. It's an excellent resource for this.</p> <p><strong>Edit 3 response:</strong></p> <p>bar = &amp;foo means: Make bar point to foo in memory</p> <p><em>Yes.</em></p> <p>*bar = foo means Change the value that bar points to to equal whatever foo equals</p> <p><em>Yes.</em></p> <p>If I have a second pointer (int *oof), then:</p> <p>bar = oof means: bar points to the oof pointer</p> <p><em>bar will point to whatever oof points to. They will both point to the same thing.</em></p> <p>bar = *oof means: bar points to the value that oof points to, but not to the oof pointer itself</p> <p><em>No. You can't do this (assuming bar is of type int *) You can make pointer pointers. (int **), but let's not get into that... You cannot assign a pointer to an int (well, you can, but that's a detail that isn't in line with the discussion).</em></p> <p>*bar = *oof means: change the value that bar points to to the value that oof points to</p> <p><em>Yes.</em></p> <p>&amp;bar = &amp;oof means: change the memory address that bar points to be the same as the memory address that oof points to</p> <p><em>No. You can't do this because the address of operator returns an rvalue. Basically, that means you can't assign something to it.</em></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload