0

In the following part of the string swap code

 end = &str[len - 1];

I am not understanding the addressing part. When I do it without the addressing part it still runs but gives me a warning that "a values of type char cannot be assigned to identity of type char". Here is the full code:

    #include<iostream>
    #include<cstring>
    using namespace std;

int main()
{
    char str[] = "This is a test";
    char *start, *end; 
    int len;
    int t; 

    cout << "Original " << str << "\n";
    len = strlen(str);
    start = str;
    end = str[len - 1];  

//this reverses the string
    while (start < end) { 

        t = *start;  
        *start = *end; 
        *end = t; 

        start++; 
        end--; 

    }
    cout << "Reversed" << str << "\n";
    system("PAUSE");
    return 0;
}
4

3 回答 3

1

我不理解寻址部分。

给定

char str[] = "This is a test";
char *start, *end; 
len = strlen(str);

thenend是指向 char 的指针,并且

end = &str[len - 1]; // `end` points to the last character (before the `\0`)

您必须使用&(address of) 运算符,因为end它是指针,因此必须将其分配给某物的地址(这里是字符串最后一个字符的地址)。

当我在没有寻址部分的情况下执行此操作时,它仍然运行

我不认为它会 - 你应该有一个编译错误

end = str[len - 1]; // invalid conversion from ‘char’ to ‘char*’
于 2017-01-09T01:41:38.427 回答
0

你应该知道 is 的类型endchar*但是 is 的类型str[len-1]char所以你需要将 type 更改str[n-1]char*,所以你需要&str[len-1]

但是如果你使用string,会有一个简单的方法:

使用来自STL的 std::reverse 方法:

std::reverse(str.begin(), str.end()); //str 应该是字符串类型

您必须包含“算法”库#include。

于 2017-01-09T01:48:10.583 回答
0

也许这可以帮助

void reverse (char word[])
{
   int left = 0;
   int right = strlen(word) - 1;

   while (left < right)
   {
      char temp = word[left];
      word[left] = word[right];
      word[right] = temp;
      left++;
      right--;
   }
   cout << word;

}

我希望这能给你这个想法。

于 2017-01-09T02:15:40.997 回答