Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You usually go through the list until you reach the tail item while counting in the meanwhile, code should be something like that:</p> <pre><code>int listLength(struct Data_Struct* item) { struct Data_Struct* cur = item; int size = 0; while (cur != null) { ++size; cur = cur-&gt;Next; } return size; } </code></pre> <p>Mind that complexity of this operation is linear with the size of the list, so it's <em>O(n)</em> and it's quite inefficient. You could store size somewhere and update with list insertions and deletes to avoid any overhead and being able to calculate it in a constant time <em>O(1)</em>.</p> <p><strong>EDIT:</strong> Didn't notice you wanted size of the whole data included into the list. In your case you can keep the same approach used for calculating the length but instead that adding <strong>1</strong> for every element you should add the total length of strings:</p> <pre><code>size += strlen(Name)+strlen(Task)+strlen(Pos); </code></pre> <p>Mind that since data inside your list element if of type <code>char*</code> the effective size of the <code>Data_Struct</code> is just 4 pointers, that's why you need to use a support function like <code>strlen</code>, otherwise you can't get <em>real</em> dimension of the strings.</p> <p>Which is the difference?</p> <pre><code>sizeof(Data_Struct) == 16 </code></pre> <p>because the <code>Data_Struct</code> type contains 4 pointers, three for pointers to char and one for the next element in the list</p> <pre><code>sizeof(Name) == sizeof(Task) == sizeof(Pos) == 4 </code></pre> <p>because these variables are of type <em>pointer to char</em>, so they are pointer, no concrete value, and it's usually 4 bytes (I'm assuming a 32 bit architecture)</p> <pre><code>strlen(Name) == length in chars of the string </code></pre> <p>because the function works exactly to calculate the length of a string.</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