简体   繁体   中英

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?

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

当str [i]为'\\ 0'时,您开始复制,因此您的字符串将以它开头并且为空。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM