Answer to Exercise 4-13, page 88
Solution by Gregory Pietsch
Write a recursive version of the function reverse(s) , which reverses the string s in place.
/*
EXERCISE 4-13 Gregory Pietsch
*/
static void swap(char *a, char *b, size_t n)
{
while (n--) {
*a ^= *b;
*b ^= *a;
*a ^= *b;
a++;
b++;
}
}
void my_memrev(char *s, size_t n)
{
switch (n) {
case 0:
case 1:
break;
case 2:
case 3:
swap(s, s + n - 1, 1);
break;
default:
my_memrev(s, n / 2);
my_memrev(s + ((n + 1) / 2), n / 2);
swap(s, s + ((n + 1) / 2), n / 2);
break;
}
}
void reverse(char *s)
{
char *p;
for (p = s; *p; p++)
;
my_memrev(s, (size_t)(p - s));
}
'The C Programming Language' 카테고리의 다른 글
Chapter 5 - Pointers and Arrays 2 (0) | 2009.03.27 |
---|---|
Chapter 4 - Functions and Program Structure 14 (0) | 2009.03.27 |
Chapter 4 - Functions and Program Structure 12 (0) | 2009.03.27 |
Chapter 4 - Functions and Program Structure 11 (0) | 2009.03.27 |
Chapter 4 - Functions and Program Structure 10 (0) | 2009.03.27 |