Ben Bacarisse
6/23/2011 11:09:00 AM
arnuld <sunrise@invalid.address> writes:
> This is a typical interview questions. I have browsed archives and came
> across solutions, both iterative and recursive. They work fine, posting
> them here if there is some problem in code that I can't see:
<snip>
> void using_recursion(char* p, char* q);
> void using_iteration(char* p);
You should really have the same API (to use a fancy term) for both.
That will show up the fact the your recursive solution is considerably
more complex then the iterative one and it might have eliminated the
problems below:
> int main(void)
> {
> /* can not reverse next commented array as it consists of const
> characters */
> /* char arr = "123" */
> char arr[10] = {'1', '2', '3', '4', '5', '\0'};
> char* p = arr;
> printf("%s\n", arr);
> printf("------------------------------\n");
> using_recursion(p, (p + (strlen(p) - 1)));
Two things:
(a) When p points to an empty string, p + strlen(p) - 1 is an invalid
pointer.
(b) Your expression is, arguably, worse because (strlen(p) - 1) is a
very large positive number when strlen(p) is zero.
> printf("%s\n", arr);
> using_iteration(p);
> printf("%s\n", arr);
>
> return 0;
> }
>
>
> void using_recursion(char* p, char* q)
> {
> char c;
> if(NULL == p || NULL == q)
This is too late. When p == NULL you can't do the calculation that
computes q. You need a set-up function that tests p (and strlen(p))
and which calls this function when all is well.
> {
> printf("Error: Invalid Args!\n");
All of your functions do this sort of thing. I'd down-grade interview
candidates that printed error message from inside "utility" code like
this; and I'd do so a little more aggressively when the error was not
sent to stderr. Part of the challenge of C is to devise a way to signal
or handle errors in utility code like this. What's often done (and I'd
do so here) is to pass the buck to the caller -- i.e. to assume that
null pointers are not passed.
> }
<snip>
--
Ben.