i need to write a function reverse_string, whose prototype is
void reverse_string( char * string). i need to use pointers rather than arrays and subscripts, and do not use the C library functions. this function should take the following as input and prints it reversed to stdout
Need help in c programming (not C# or C++)?
void reverse_string(char* string)
{
char* ptr = string;
char c = *ptr;
if(c != '\0')
{
reverse_string(++ptr);
printf("%c",c); // if %c is format symbol for type char...
}
}
this should work I think...it's a recursive thing...
Reply:off handed solution..
try something like
for(i=0,j=strlen(string);i%26lt;=j;++i,++j)
{
swap string[i] and string[j]
}
homework question eh? If I didn't suspect so, I'd have written out a working code ;)
Reply:Probably not an elegant solution, but you could do the following:
1. Using a While loop, locate the '/0' indicating the end of the string. You can count the number of characters, starting with 0 (stored in int x for this example).
2. Make a new "char * newString"
3. Run through a For loop "for(int i = 0; i %26lt; x; i++)
4. Build the newString setting the i-th character equal to string's (x-i)-th character. Sorry, it's late and I don't recall pointer math right now, so I can't write down the proper syntax for this
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment