C++字符串和指针

Dan*_*Dan 12 c++ string pointers

我正在学习C++,目前我正在使用字符串和指针.

我正在按照练习册和我创建的以下问题之一:

#include <iostream>
#include <string>

using namespace std;

int main(void){
    string * firstName=nullptr;
    string * lastName=nullptr;
    string * displayName=nullptr;

    cout << "Enter your first name: " << endl;
    getline(cin,*firstName);

    cout << "Enter your last name: " << endl;
    getline(cin,*lastName);

    displayName=new string;
    *displayName= *lastName + ", " + *firstName;

    cout << "Here's the information in a single string: " << displayName;
    cin.get();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为了使用更多的指针,我试图将它与字符串混合在一起,并因此而使解决方案变得更加复杂.当我运行这个时,我得到一个"未处理的异常:访问冲突读取位置xxxxxxxxx".

有人可以通过仍然使用指针和字符串而不是char数组(我已经弄清楚如何做)来建议解决方案吗?

das*_*ght 15

这是因为在使用对象之前没有分配对象:

string * firstName = new string();
//...
delete firstName;
Run Code Online (Sandbox Code Playgroud)

值得补充的是,在这种情况下使用指针是毫无意义的:标准C++库中的字符串对象从堆中分配字符串的数据; 无论如何,字符串通常不会超过一对指针.


sky*_*all 5

pointers我想,你根本不想使用。strings您无需指针即可使用。

#include <iostream>
#include <string>

using namespace std;

int main(void){
  string firstName;
  string lastName;
  string displayName;

  cout << "Enter your first name: " << endl;
  getline(cin,firstName);

  cout << "Enter your last name: " << endl;
  getline(cin,lastName);

  displayName= lastName + ", " + firstName;

  cout << "Here's the information in a single string: " << displayName;
  cin.get();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

否则,如果您需要指针,则必须为变量分配内存:

  cout << "Enter your first name: " << endl;
  firstName = new string();
  getline(cin,*firstName);
Run Code Online (Sandbox Code Playgroud)

...并使用解引用运算符 ( ) 打印结果*

cout << "Here's the information in a single string: " << *displayName;
Run Code Online (Sandbox Code Playgroud)