简体   繁体   中英

C++ strings and pointers

I'm learning C++ and currently I'm working with strings and pointers.

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".

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)?

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; strings are usually not much more than a pair of pointers anyway.

I think, you don't want to use pointers at all. You can work with strings without pointers.

#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).

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:

#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.

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.

Read the 10 commandments of c programming . 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.

That's actually what you're doing here. Your pointers point nowhere (see the assignments to 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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