In: Computer Science
Write a function
void reverse(char * s)
that reverses the string passed as an argument. Your code should use pointer arithmetic (it may increment and decrement pointers, but it may not use array indexing).
Here is a piece of code that shows the behavior of reverse:
char buf[100];
strcpy(buf, “hello”);
reverse(buf);
printf(“%s\n”, buf); // output should be olleh
#include <stdio.h>
#include <string.h>
void
reverse(char * s) {
char temp;
char *last = s;
while(*last) {
last++;
}
last--;
char *first = s;
while(first < last) {
temp = *first;
*first = *last;
*last = temp;
first++;
last--;
}
}
int
main() {
char buf[100];
strcpy(buf, "hello");
reverse(buf);
printf("%s\n", buf); // output should be olleh
return 0;
}
if this Answer is helpful to you please give positive rating.
if any doubts please provide a comment i will try to clarify your doubts