user550738
user550738

Reputation:

why is my 'reverse' string C function not working?

I'm trying to write a function to reverse the characters in a string in C, but it's not working.

This is what I have:

/* ... the  */
char str[1000];
strcpy(&str[0], &text[0]); // get the values from existing 'char text[1000]' 

if (DEBUG) printf("DEBUG: str value before reverse: %s\n", str); 
// reverse the string
reverse(&str[0]);
if (DEBUG) printf("DEBUG: str value after reverse: %s\n", str); 
/* ... */

After calling 'reverse', my output looks like this:

DEBUG: str value before reverse: this is a line of text
DEBUG: str value after reverse: 

Here's my function:

void reverse(char * str)
{
  char str2[1000];
  int i = 0;
  // find the null in str
  while (str[i] != '\0') {
    i++;
  }
  // now put the chars from str into str2 in the reverse order
  int j = 0;
  while (i >= 0) {
    str2[j] = str[i];
    i--;
    j++;
  }
  str2[j] = '\0';
  // now str2 contains the reverse of str, copy it to str
  strcpy(&str[0], &str2[0]);
  return;
}

What's wrong with it? And is there an easier way to reverse a string?

Upvotes: 0

Views: 145

Answers (3)

Jon
Jon

Reputation: 437336

What's wrong with it?

After the first loop completes, str[i] is equal to 0. Therefore the first iteration of the second loop stores the null terminator at the first position of str2, making it effectively a string of length 0. Of course it then goes on and writes additional characters to the buffer, but those will be ignored by any function you use.

And is there an easier way to reverse a string?

Sure. For example, this implementation reverses a string in-place without allocating additional buffers:

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;
}

Upvotes: 1

user550738
user550738

Reputation:

I figured it out.

After the first while loop, i is the location of the '\0' and I'm making it the first character of str2, so str is always empty string.

Upvotes: 0

CMoi
CMoi

Reputation: 846

You start copying when str[i] is '\0', so your string will start with it and be empty.

Upvotes: 0

Related Questions