在 C++ 中使用指针处理字符串

Use of Pointers for string handling in C++

我正在学习 C++ 的基础知识。代码按我的意愿运行良好,但我想知道的是 case 2 中的功能是交换字符串,基本上是怎么回事? array[pos1 -1] 处的字符串是否被复制到 temp 然后交换或者只是要交换的字符串的地址正在重新分配?

#include <iostream>
using namespace std;

int main()
{
   const char *array[] {"Albert",
                        "Newton",
                        "Gallilio",
                        "Hawking"};

   cout << "What do you want to do:\n1-Display Strings\n2-Swap Positions" << endl;
   unsigned short int choice{};
   cin >> choice;

   switch (choice)
   {
    case 1:
    {
    for (short int i = 0; i < _countof(array); i++)
    {
        cout << "\n" << array[i];
    }
    cout << endl;
    break;
    }
    case 2: 
    {
    short int pos1{}, pos2{};
    const char *temp{ nullptr };

    cout << "Whom do you want to swap? Enter two numbers when prompted: " << endl;
    cout << "Swap --- "; cin >> pos1;
    cout << "With --- "; cin >> pos2;

    temp = array[pos1 - 1];
    array[pos1 - 1] = array[pos2 - 1];
    array[pos2 - 1] = temp;

    cout << "\nChanged Order is";

    for (short int i{} ; i < _countof(array); i++)
    {
        cout << "\n" << array[i];
    }
    cout << endl;
    break;
    }
    default:
    cout << "\a";
  }
return 0;
}

我们假设 pos1 是 1,pos2 是 2。

然后 array[pos1-1] 持有一个指向字符 A 的指针,该字符被解释为由空字符终止的 Albert[=14=] 字符串。同样 array[pos2-1] 持有指向字符串 Newton[=16=].

的指针

case 2被命中时,temp被初始化为一个空指针。然后 temp 被赋值以保存指向 Albert[=14=] 的指针的副本。然后 array[pos1-1] 被重新分配以保存指向 Newton[=16=] 的指针。然后我们希望 array[pos2-1] 指向 Albert[=14=],但是 array[pos1-1] 中的指针值不再指向那里。这就是temp中copy进来的地方,因为它仍然是指向Albert[=14=]的指针,所以这个指针被复制到array[pos2-1].