Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The only actual error is that you don't check the return value of <code>malloc</code> for null.</p> <p>The name <code>itoa</code> is kind of already taken for a function that's non-standard, but not that uncommon. It doesn't allocate memory, rather it writes to a buffer provided by the caller:</p> <pre><code>char *itoa(int value, char * str, int base); </code></pre> <p>If you don't want to rely on your platform having that, I would still advise following the pattern. String-handling functions which return newly allocated memory in C are generally more trouble than they're worth in the long run, because most of the time you end up doing further manipulation, and so you have to free lots of intermediate results. For example, compare:</p> <pre><code>void delete_temp_files() { char filename[20]; strcpy(filename, "tmp_"); char *endptr = filename + strlen(filename); for (int i = 0; i &lt; 10; ++i) { itoa(endptr, i, 10); // itoa doesn't allocate memory unlink(filename); } } </code></pre> <p>vs.</p> <pre><code>void delete_temp_files() { char filename[20]; strcpy(filename, "tmp_"); char *endptr = filename + strlen(filename); for (int i = 0; i &lt; 10; ++i) { char *number = itoa(i, 10); // itoa allocates memory strcpy(endptr, number); free(number); unlink(filename); } } </code></pre> <p>If you had reason to be especially concerned about performance (for instance if you're implementing a stdlib-style library including <code>itoa</code>), or if you were implementing bases that <code>sprintf</code> doesn't support, then you might consider not calling <code>sprintf</code>. But if you want a base 10 string, then your first instinct was right. There's absolutely nothing "incorrect" about the <code>%d</code> format specifier.</p> <p>Here's a possible implementation of <code>itoa</code>, for base 10 only:</p> <pre><code>char *itobase10(char *buf, int value) { sprintf(buf, "%d", value); return buf; } </code></pre> <p>Here's one which incorporates the snprintf-style approach to buffer lengths:</p> <pre><code>int itobase10n(char *buf, size_t sz, int value) { return snprintf(buf, sz, "%d", value); } </code></pre>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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