Code:
#include <stdio.h>
#include <stdlib.h> /* for malloc */
#include <string.h> /* for strlen */
char* rot13(char*);
int main(void)
{
char string[] = "I'm a string";
char *answer = rot13(string);
if ( answer != NULL ) {
printf( "%s\n", answer );
free( answer );
}
getchar();
return 0;
}
char* rot13(char* string)
{
size_t len = strlen( string ); /* better than for(;string[len]!='\0';len++); */
char *ret = malloc ( len + 1 ); /* allow for the \0 as well, and no need for static */
if ( ret != NULL ) { /* always check malloc returns */
int i;
for (i=0; string[i]!='\0'; i++)
{
char c = string[i];
/* character constants are more readable, but it still assumes ASCII */
/* In EBCDIC for example, 'A' + 13 isn't even a character */
if (c >= 'A' && c <='M') c = c + 13;
else if (c >= 'N' && c <='Z') c = c - 13;
else if (c >= 'a' && c <='m') c = c + 13;
else if (c >= 'n' && c <='z') c = c - 13;
ret[i] = c;
}
ret[i]='\0';
}
return ret;
}
Perhaps with the static thing, you were thinking of this?
Code:
char *foo ( void ) {
static char aReturnableArray[10];
strcpy( aReturnableArray, "hello" );
return aReturnableArray;
}
> which sometimes fails to return the proper length . please correct if i am wrong
I've never seen strlen() fail, unless it's because of some other mistake in the code.
Besides, how do you think strlen() is implemented - pretty much the way you've implemented it, so if strlen() is flawed, then so is your code.