用指针符号反转cstring时出现意外结果

用指针符号反转cstring时出现意外结果

我将两个c字符串(一个包含字符,另一个为空)传递给一个函数,该函数应该采用包含字符的c字符串,并用从后面读取的字符串填充空的c字符串。操作简单,但不起作用。我只是不知道我在做什么错。

#include <iostream>
#include <cstring>

using namespace std;

void magic(char*, const char*, int);

int main()
{
   char string1[20];
   char string2[] = "This is a test";
   char *str1 = string1;
   char *str2 = string2;
   int stringsize = strlen(string2);
   magic(str1, str2, stringsize);
   return 0;
}

void magic(char* string1, const char* string2, int stringsize)
{
   cout << string2 << endl; //here it prints as expected
   *(string1 + stringsize) = '\0';
   string1 = string1 + stringsize - 1;
   for(;*string2 != '\0' ;string1--, string2++)
   {
      *string1 = *string2;
   }
   cout << string1 << endl; //blank space is printed - expected "This is a test" reversed
   cout << string2 << endl; //blank space is printed - expected "This is a test"
}

最佳答案

如果使用非常简单的字符串遵循for循环中的步骤,则可以在逻辑中看到问题。比方说

string1 = "This";


在循环的第一次迭代中,

string1 = "This";
string2 = "T";


在循环的第二次迭代中,

string1 = "his";
string2 = "hT";


在循环的第三次迭代中,

string1 = "is";
string2 = "ihT";


在循环的第四次迭代中,

string1 = "s";
string2 = "sihT";


在循环的第五次迭代中,

string1 = "";
string2 = "?sihT";  // You go past the start of the array.


因此,在for循环结束之后,您需要增加string2以确保其指向数组的开始。

void magic(char* string1, const char* string2, int stringsize)
{
   cout << string2 << endl;
   *(string1 + stringsize) = '\0';
   string1 = string1 + stringsize-1;
   for(;*string2 != '\0' ;string1--, string2++)
   {
      *string1 = *string2;
   }

   // Add this.
   string1++;

   cout << string1 << endl; // This is now the reversed string.
   cout << string2 << endl; // This is now the empty string since
                            // you kept incrementing it in the for
                            // loop until you reached the end of the
                            // string.
}

关于c++ - 用指针符号反转cstring时出现意外结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31900633/

10-14 11:00