这个功能是如何工作的?字符* getname(); C++

How does this function work? char* getname(); C++

我开始学习如何用 C++ 编写代码。 我一直在阅读 c++ primer plus(第 5 版)一书,遇到了一个我不完全理解的示例程序。基本上,该程序会询问您的姓氏并为您提供其存储位置的地址:

#include <iostream>
#include <cstring>
using namespace std;
char* getname();
int main();
{
  char* name;
  name = getname();
  cout << name << " at " << (int*)name << endl;
  delete [] name;

  name = getname();
  cout << name << " at " << (int*)name << endl;
  delete [] name;

  return 0;
}

char* getname()
{
  char temp[80];
  cout << "Enter last name: ";
  cin >> temp;
  char* pn = new char [strlen(temp)+1];
  strcpy(pn, temp);

  return pn;
}

我不太明白为什么 char* getname() 函数需要取消引用运算符。我在整体上理解这个程序有点困难,呵呵。 抱歉,如果这是一个愚蠢的问题,但我很困惑。就这样。谢谢!...

name - 它是指向序列中第一个字符的指针。 std::cout<< - 有不同的行为取决于你给他什么。

  • 如果它的指针指向序列中的第一个字符 (char* name) - cout 打印此序列。
  • 如果它的指针指向int数字- cout这个数字在内存中的打印地址(0x1105010)

(int*) - 转换为指向 int.

的指针