简体   繁体   English

C ++字符串和指针

[英]C++ strings and pointers

I'm learning C++ and currently I'm working with strings and pointers. 我正在学习C ++,目前我正在使用字符串和指针。

I'm following an exercise book and for one of the questions I've created the following: 我正在按照练习册和我创建的以下问题之一:

#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;
}

In a bid to use more of pointers I've tried to mix it together with strings and have made the solution more complex for this reason. 为了使用更多的指针,我试图将它与字符串混合在一起,并因此而使解决方案变得更加复杂。 When I run this I get a "Unhandled Exception: Access violation reading location xxxxxxxxx". 当我运行这个时,我得到一个“未处理的异常:访问冲突读取位置xxxxxxxxx”。

Can someone please suggest a solution to this by still using pointers and strings instead of char arrays (which I've already figured out how to do)? 有人可以通过仍然使用指针和字符串而不是char数组(我已经知道如何做)来建议解决方案吗?

This is because you have not allocate your objects prior to using them: 这是因为在使用对象之前没有分配对象:

string * firstName = new string();
//...
delete firstName;

It's worth adding that using pointers in this situation is, well, pointless: string objects in the standard C++ library allocate the data for the string from the heap; 值得补充的是,在这种情况下使用指针是毫无意义的:标准C ++库中的字符串对象从堆中分配字符串的数据; strings are usually not much more than a pair of pointers anyway. 无论如何,字符串通常不会超过一对指针。

I think, you don't want to use pointers at all. 我想,你根本不想使用pointers You can work with strings without 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;
}

Othewise, if you need pointers, you have to allocate memory for variables: 其他,如果你需要指针,你必须为变量分配内存:

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

...and print result with dereference operator ( * ): ...并使用解除引用运算符( * )打印结果:

cout << "Here's the information in a single string: " << *displayName;

It would look like this: 它看起来像这样:

int main()
{
    std::string* s = new std::string;
    std::getline(std::cin, *s);
    std::cout << *s;
    delete s;
}

But there is really no reason to do so, just define a normal string variable on the stack. 但实际上没有理由这样做,只需在堆栈上定义一个普通的字符串变量。

You are getting errors because you are using strings as pointers and you are not initializing them. 您正在收到错误,因为您使用字符串作为指针并且您没有初始化它们。 A correct way of doing this would be: 这样做的正确方法是:

#include <iostream>
#include <string>

using namespace std;

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

    cout << "Enter your first name: " << endl;
    cin >> firstName;

    cout << "Enter your last name: " << endl;
    cin >> lastName;

    displayName = firstname + ' ' + lastName;


    cout << "Here's the information in a single string: " << displayName << endl;
    return 0;
}

You may actually use pointers to strings, but they are meant to be used as local object and passed around as references (or const references, if you wish). 实际上,您可以使用指向字符串的指针,但它们应该用作本地对象并作为引用传递(或者如果您愿意,则传递给const引用)。

The access violation is because you are dereferencing a null pointer. 访问冲突是因为您要取消引用空指针。

Null pointer is set here 在这里设置空指针

string * firstName=nullptr;

and then dereferenced here 然后在这里取消引用

getline(cin,*firstName)

You need to have firstname 'point' to something ( a string in this case ). 你需要有一个名字'指向'某事(在这种情况下是一个字符串)。 Here's a modified version without the exceptions. 这是一个没有例外的修改版本。

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

    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->c_str();
    cin.get();
    return 0;
}

Since you're using nullptr , I guess a full-blown C++11 solution is equally fine: 既然你正在使用nullptr ,我想一个成熟的C ++ 11解决方案同样很好:

#include <iostream>
#include <memory>
#include <string>

using namespace std;

int main(void){
    unique_ptr<string> firstName(new string());
    unique_ptr<string> lastName(new string());
    unique_ptr<string> displayName(new string());

    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;
}

Of course using nullptr was not what you wanted: you need to allocate the resources you want to use. 当然使用nullptr并不是你想要的:你需要分配你想要使用的资源。

Note that using pointers in these simple cases is shooting yourself in the foot, both syntax-wise and bug-wise. 请注意,在这些简单的情况下使用指针就是在语法方面和错误方面将自己射入脚中。

EDIT I corrected the code (a forgotten parenthesis and the * on the last line of main ), it succesfuly compiles and runs on GCC 4.7. 编辑我纠正了代码(一个被遗忘的括号和main最后一行的* ),它成功地编译并运行在GCC 4.7上。

Read the 10 commandments of c programming . 阅读c编程10条诫命 Some are more or less obsolete for today's devs, but some are still important, such as the second one: 对于今天的开发者来说,有些或多或少已经过时,但有些仍然很重要,例如第二个:

Thou shalt not follow the NULL pointer, for chaos and madness await thee at its end. 你不应该遵循NULL指针,因为混乱和疯狂等待着你。

That's actually what you're doing here. 那就是你在这里做的事情。 Your pointers point nowhere (see the assignments to std::nullptr ). 你的指针无处可寻(见std::nullptr的赋值)。

To correct this, you have to assign a new object of the right class/struct to the pointer. 要纠正这个问题,您必须将正确的类/结构的新对象分配给指针。 Also, don't forget to delete it later on: 另外,不要忘记稍后删除它:

std::string *myString = new std::string(); // create an object and assign it's address to the pointer

// do something with it... (this part has been right)

delete myString; // free the memory used by the object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM