Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>"Why is sizeof being used?"</strong></p> <p>To understand why sizeof() is being used, you must first have a basic understanding of the structure and the variable it is used to define.</p> <pre><code>static struct item { char code; float price; } table[] = { {'a', 3.29}, {'b', 2.99}, {'c', 0.59}, {'d', 1.59}, {'e', 2.39} }; </code></pre> <p>This declares a structure type called <em>item</em> which consists of two variables - <em>code</em> which has a type of <em>char</em> and <em>price</em> which has a type of <em>float</em>. Using the following statement:</p> <pre><code>sizeof(struct item) </code></pre> <p>Provides the size of the structure itself... a char, 1 byte and a float, 4 bytes.</p> <p>The code then defines a struct item array called table[] and initializes it with multiple values. In this particular case there are five chars and five floats (for a total of 25 bytes). So, by taking the sizeof(table) and dividing it by the sizeof(struct item), we are given the total value of struct items in the array (25 / 5 = 5).</p> <p>You may ask, why not just say i &lt; 5 ? Afterall, you can see that there are five struct items in the table array. However, if this is a huge table you may not want to count the number of structures in the array. This also makes it much easier to maintain later on down the road.</p> <p><strong>What exactly is the value of "i" each time the loop is executed?</strong></p> <p>The first and last parts of the for(;;) loop provides the answer:</p> <pre><code>for (i = 0; i &lt; sizeof(table)/sizeof(struct item) &amp;&amp; table[i].code != *item_code; i++); </code></pre> <p>So, i is initialized with the value 0. During each successive iteration through the loop, i is incremented by 1 (i++).</p> <p>Therefore, i will continue to increase by 1 until one of the following boundaries has been reached:</p> <pre><code>i == 5 //(sizeof(table) / sizeof(struct item)) table[i].code == *item_code </code></pre> <p>I hope this helps!</p>
    singulars
    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.
    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