Hi,
I am trying to code a trival interview question of reversing a string.
This is my code:
#include <string.h>
char* rev( char* str)
{
int i,j,l;
l = strlen(str);
for(i=0,j=l-1; i<l/2 ; i++, j--)
{
str[i] = (str[i] + str[j]);
str[j] = str[i] - str[j];
str[j] = str[i] - str[j];
}
return str;
}
int main()
{
char *str = " hello";
printf("\nthe reverse is %s ...", rev(str));
return 1;
}
Basically, this one gives a segmentation fault.
I have following questions:
I get segmentation fault probably because, the characters add up to something not defined in ascii and hence I cannot store them back as characters, I am using www.codepad.org [I wonder if it supports just ascii !!] . Is my understanding correct or there is something else to it.
How do I correct the problem , for the same platform [I mean swapping in place for codepad.org]
Here I have to use an additional integer l to calculate length. So to save a single char space by swapping in place .. I am using an extra int !!! .. just to impress the inteviewer :) ... Is this approach eve worth it !!!
This one is for those who are interested in writing unit tests/API tests . I want to have a robust implementation so what can be possible test cases. I assume that if interviewer asks such a simple question .. he definitely wants some very roboust implementation and test cases. Few that I thought off:
passing empty strings passing integer
strings passing integer array instead of char array.
very long string ,
single char string string of special chars.
Any advise/suggestions would be helpful.