0

For a class I am writing a snippet of code to take a pointer that points to a string, reverse it, and set it to another string pointer. I get the code running fine and it reverses the string well. The problem occurs when I try to print the value of the reversed pointer. Here is the code:

char * reverse (char *dest, char *src)
{
  int length=0;
  char c;

  while(*src != '\0')
  {
    src++;
    length++;
  }
  for(int a = 0; a<length; a++){
    c=(*--src);
    //Print out the value of c
    printf("Before dest: %c\n", c);
    *dest= c;
    //Print out the value of *dest
    printf("-After dest: %c\n", *dest);
    dest++;
  }
  printf("Input was: %s\n", src);
  printf("Output should be: %s\n",dest);
  return dest;
}

And here is what it returns with input being "hello" and a pointer that points to a blank array of chars.

Before dest: o
-After dest: o
Before dest: l
-After dest: l
Before dest: l
-After dest: l
Before dest: e
-After dest: e
Before dest: H
-After dest: H
Input was: Hello
Output should be: ù.█
Reverse ù.█

Before and after dest lines are there for debugging. The reverse line is what is returned from the function The output is different every time. I am completely dumbfounded and my professors say that this should be correct. Any help is appreciated

0 Answers0