Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Problems:</p> <ol> <li><code>length</code> isn't a function. <code>strlen</code> is, but you probably shouldn't call it in a loop - <code>b1</code>'s length won't change on us, will it? Also, it returns a <code>size_t</code>, which may be the same size as <code>int</code> on your platform but will be unsigned. This can (but usually won't) cause errors, but you should do it right anyway.</li> <li><code>a1</code> only has enough space for the first string, because the compiler doesn't know to allocate extra stack space for the rest of the string since. If you provide an explicit size, like <code>[100]</code>, that should be enough for your purposes. If you need robust code that doesn't make assumptions about what is "enough", you should look into <code>malloc</code> and friends, though that may be a lesson for another day.</li> <li>Your loop stops too early. <code>i &lt; b1_len</code> (assuming you have a variable, <code>b1_len</code>, that was set to the length of <code>b1</code> before the loop began) would be sufficient - <code>strlen</code> doesn't count the <code>'\0'</code> at the end.</li> <li>But speaking of counting the <code>'\0'</code> at the end, a slightly more efficient implementation could use <code>sizeof a1 - 1</code> instead of <code>strlen(a1)</code> in this case, since <code>a1</code> (and <code>b1</code>) are declared as arrays, not pointers. It's your choice, but remember that <code>sizeof</code> won't work for pointers, so don't get them mixed up.<br> EDIT: New problems:</li> <li><code>char *p = malloc(/*some*/); p = /* something */</code> is a problem. <code>=</code> with pointers doesn't copy contents, it copies the value, so you're throwing away the old pointer value you got from <code>malloc</code>. To copy the contents of a string into a <code>char *</code> (or a <code>char []</code> for that matter) you'd need to use <code>strcpy</code>, <code>strncpy</code>, or (my preference) <code>memcpy</code>. (Or just a loop, but that's rather silly. Then again, it may be good practice if you're writing your own <code>strcat</code>.)</li> <li>Unless you're using C++, I wouldn't cast the return value of <code>malloc</code>, but that's a religious war and we don't need one of those.</li> <li><p>If you have <code>strdup</code>, use it. If you don't, here is a working implementation:</p> <pre><code>char *strdup(const char *c) { size_t l = strlen(c); char *d = malloc(l + 1); if(d) memcpy(d, c, l + 1); return d; } </code></pre> <p>It is one of the most useful functions not in the C standard library.</p></li> </ol>
 

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