Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For solutions, see <a href="http://clc-wiki.net/wiki/K%26R2_solutions:Chapter_5:Exercise_5" rel="nofollow noreferrer">CLC Wiki page</a>.</p> <p>Now some comments about your code:</p> <p>For <code>strncmp</code>:</p> <pre><code>if(strlen(s) == strlen(t)) { </code></pre> <p>You don't need this check. <code>strlen()</code> traverses the string, so you are going to process the strings twice if the lengths are equal. This can get expensive. In general, low-level functions like these, which can be called a lot in any program should be efficient (although premature optimization is the root of all evil!). Also, you're calling <code>strlen()</code> again for both the strings if the lengths aren't equal. In addition to being expensive, it is wrong too, but we will come to that later. About your <code>while</code> loop:</p> <pre><code>while(*s == *t &amp;&amp; *s &amp;&amp; n) n--, s++, t++; </code></pre> <p>Why abuse the comma operator? I would simplify and write the above as (untested, after all, this is an exercise <em>you</em> are solving!):</p> <pre><code>while (*s &amp;&amp; *t &amp;&amp; *s == *t &amp;&amp; n--) { s++; t++; } if (!n) return 0; else return *s - *t; </code></pre> <p>Your return values are wrong. <code>strncmp()</code> should return 0, less-than 0, or greater-than 0 depending upon whether the first <code>n</code> characters of the first string compare equal to, less than, or greater than (lexicographically) the second string.</p> <p>Similarly, you should change your <code>strncpy()</code> and <code>strncat2()</code> functions. I haven't looked at those two in detail, but since this is an exercise, you probably want to make the changes yourself anyway.</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. 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