Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen using calloc in C what is stored at the address of the pointer?
    primarykey
    data
    text
    <p>I'm having a hard time understanding this program to illustrate pointers (from <a href="http://theocacao.com/document.page/234" rel="nofollow">http://theocacao.com/document.page/234</a>):</p> <p>Below I don't understand why:</p> <pre><code>int * currentSlot = memoryBlock </code></pre> <p>isn't using <code>&amp;memoryBlock</code>. I read the comment but don't get it. What is memoryBlock putting in there that &amp;memoryBlock wouldn't? Won't both return the pointer to the set of ints created with calloc (assuming I understand what's been done that is)? What is really in <code>* memoryBlock</code> after <code>calloc</code>?</p> <p>Then here, <code>*currentSlot = rand();</code>, how does the dereferencing work here? I thought the dereference would stop *currentSlot from giving the value of the memory address (the reference) to the actual value (no longer a reference but the value).</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; // for calloc and free #include &lt;time.h&gt; // for random seeding main () { const int count = 10; int * memoryBlock = calloc ( count, sizeof(int) ); if ( memoryBlock == NULL ) { // we can't assume the memoryBlock pointer is valid. // if it's NULL, something's wrong and we just exit return 1; } // currentSlot will hold the current "slot" in the, // array allowing us to move forward without losing // track of the beginning. Yes, C arrays are primitive // // Note we don't have to do '&amp;memoryBlock' because // we don't want a pointer to a pointer. All we // want is a _copy_ of the same memory address int * currentSlot = memoryBlock; // seed random number so we can generate values srand(time(NULL)); int i; for ( i = 0; i &lt; count; i++ ) { // use the star to set the value at the slot, // then advance the pointer to the next slot *currentSlot = rand(); currentSlot++; } // reset the pointer back to the beginning of the // memory block (slot 0) currentSlot = memoryBlock; for ( i = 0; i &lt; count; i++ ) { // use the star to get the value at this slot, // then advance the pointer printf("Value at slot %i: %i\n", i, *currentSlot); currentSlot++; } // we're all done with this memory block so we // can free it free( memoryBlock ); } </code></pre> <p>Thank you for any help.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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.
 

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