2
\$\begingroup\$

Rewrite appropiate programs from earlier chapters and exercises with pointers instead of array indexing. Good posibilities include getline(Chapter 1 and 4), atoi, itoa, and their variants(Chapters 2, 3, and 4), reverse(Chapter 3), and strindex and getop(Chapter 4)

Here is my solution:

static char *hidden(int n, char *s) {
 char *p;
 if(n / 10) {
 p = hidden(n / 10, s);
 }
 else {
 p = s;
 }
 *p++ = n % 10 + '0';
 *p = '0円';
 return p;
}
char *itoa(int n, char *s) {
 if(n < 0) {
 *s = '-';
 hidden(-n, s + 1);
 }
 else {
 hidden(n, s);
 }
 return s; /* pointer to first char of s*/
}

itoa is a wrapper for the function hidden. The function hidden returns a pointer to the next free slot in the array s. At the deepest level of recursion it returns a pointer to the first element (the else branch) of the array.

asked Feb 5, 2014 at 14:38
\$\endgroup\$
3
  • \$\begingroup\$ I think that this is the most relevant function that needs pr, the other ones are quite simple. If you want to see them: drive.google.com/… \$\endgroup\$ Commented Feb 5, 2014 at 14:48
  • \$\begingroup\$ Please give a better name (and some explanatory comments) to your hidden function. It's hard to tell what the function does. \$\endgroup\$ Commented Feb 5, 2014 at 15:25
  • \$\begingroup\$ There is absolutely no reason to use recursion for this. It is hard to read, inefficient and dangerous. I think the classic K&R implementation of this algorithm is hard to beat in terms of efficiency. (But of course, K&R code is always an unreadable mess, filled with dangerous programming practice, so that snippet would need a code review of its own.) \$\endgroup\$ Commented Feb 6, 2014 at 14:04

1 Answer 1

2
\$\begingroup\$

The standard version of itoa takes a parameter named base (which you have assumed is 10).

You probably don't need a second hidden function; this would do instead:

if (n < 0)
{
 *s++ = '-';
 n = -n;
}
// ... itoa implementation continues here ...

Recursing is clever; you could also probably do it with two loops instead (untested code ahead):

i = 1;
while ((i * 10) <= n)
 i *= 10;
for (; i != 0; i /= 10)
{
 int x = n / i;
 *p++ = (char)(x % 10 + '0');
 n -= (x * i);
}
assert(n == 0);
answered Feb 5, 2014 at 16:17
\$\endgroup\$
1
  • \$\begingroup\$ There is no standard version of itoa. As in: how it should behave isn't specified anywhere. \$\endgroup\$ Commented Feb 6, 2014 at 13:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.