-2

How can I reverse a string in C by just giving a char* and the length as input parameters and recieving the reversed string as output? Also, without using the strrev function. Just by usign loops?

EDIT: Okay thats how I did it now:

char*  __stdcall Reverse(char *str, int length, char* *out)
{

 char *s = str;

    char *end = s + length - 1;
    for (; s < end; ++s, --end) {
        char ch = *end;
        *end = *s;
        *s = ch;
    }
      *out = str;
}
Dark Side
  • 695
  • 2
  • 8
  • 18
  • why do you want to do that? – Joe Mar 26 '15 at 15:17
  • 2
    If this is for a class, you should come up with more than that on your own (or at least try searching first - [reverse a string in c](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=reverse%20a%20string%20in%20c)) – crashmstr Mar 26 '15 at 15:18

1 Answers1

2
#include <string.h>

char *strrev(char *str)
{
  char *p1, *p2;

  if (! str || ! *str)
        return str;
  for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2)
  {
        *p1 ^= *p2;
        *p2 ^= *p1;
        *p1 ^= *p2;
  }
  return str;
}

#include <stdio.h>

int main(int argc, char *argv[])
{
  while (--argc)
  {
        printf("\"%s\" backwards is ", *++argv);
        printf("\"%s\"\n", strrev(*argv));
  }
}

You can implement your own strrev (I took it from here). Try c strrev source as a Google query.

ForceBru
  • 43,482
  • 10
  • 63
  • 98