Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The * operator is what we call the <a href="http://en.wikipedia.org/wiki/Dereference_operator" rel="nofollow noreferrer">dereference operator</a>. To understand what it does, you must understand exactly what a pointer is.</p> <p>When you do</p> <pre><code>char *p; </code></pre> <p>the "variable" p does not use the same amount of memory as a normal char, it uses more memory: it uses the amount of memory needed to correctly identify a memory position in your computer. So, let's say you use a 32-bit architecture, the variable p occupies 4 bytes (not the 1 byte you would expect from a char).</p> <p>So, when you do</p> <pre><code>p = a; </code></pre> <p>you see clearly that you are changing the contents of the variable p, that is, you are putting another 32-bit number inside it: you are changing the address it is pointing to.</p> <p>After that line executes, the value of p is the memory address of the character array a.</p> <p>Now for the <strong>dereference operator</strong>. When you do</p> <pre><code>*p = 'Z'; </code></pre> <p>you are telling the compiler that you want to store the value 'Z' ON THE ADDRESS pointed by p. So, the value of p remains the same after this line: it continues to point to the same address. It's the value of <em>this address</em> that has changed, and now contains 'Z'.</p> <p>So, the final effect of</p> <pre><code>char a[] = {'a', 'b', 'c'}; char p = a; *p = 'Z'; </code></pre> <p>is the same as changing the first position of the array a to 'Z', that is:</p> <pre><code>char a[] = {'a', 'b', 'c'}; a[0] = 'Z'; </code></pre> <p><strong>NOTE:</strong> there is a difference when making a pointer point to an array: the variable that contains the array contains only the address of the first element, so <em>a</em> is the same as "the starting address of the array".</p> <p>Usually you will see the &amp; operator. It is an operator used to obtain the memory address of a variable. For example:</p> <pre><code>int number = 42; int pointer = &amp;number; printf("%d", *pointer); </code></pre> <p>Here we have them all. The first line creates an integer variable and stores 42 inside it.</p> <p>The second line creates a pointer to an integer, and stores <strong>the address of</strong> the variable number inside it.</p> <p>The third line reades <strong>the value on the address pointed by</strong> the pointer.</p> <p>So, the trick is to read *x as <strong>on the address pointed by x</strong> and &amp;x as <strong>the address of x</strong>.</p>
 

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