13

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

simont
  • 68,704
  • 18
  • 117
  • 136
Dan
  • 769
  • 2
  • 8
  • 23
  • 3
    You are not allocating the strings, and then you pass a null pointer the to `getline()` function... just change all of the `string *x = nullptr;' to `string x;` or allocate the strings like you do with `displayName` before you pass them to `getline()` – Yaniro Mar 04 '12 at 12:23
  • 1
    If you are just beginning to "learn C++", you shouldn't be going anywhere near raw pointers. They're a difficult, advanced, niche part of C++ that you shouldn't need for most "normal" programming activities. – Kerrek SB Mar 04 '12 at 12:25
  • This [video snippet](http://www.youtube.com/watch?v=i49_SNt4yfk) was always very inspiring when I was confused about pointers ;-) – Frank Bollack Mar 04 '12 at 12:31
  • 2
    If the book really suggests you to use raw pointers to std::strings for simple local variables, throw it away. – PlasmaHH Mar 04 '12 at 12:58
  • 2
    @KerrekSB: " you shouldn't be going anywhere near raw pointers" I'd recommend the opposite. Start with pointers, program in C style, and stay away from advanced concepts like strings and STL. After few months, switch to STL. "They're a difficult, advanced" They're fundamental part of C++ ("basic literacy" level), and you must learn them. Without understanding them you won't be able to do implement your own containers and won't really understand how STL works. Somebody who can't implement linked list can't be called a programmer, you know... – SigTerm Mar 04 '12 at 14:25

7 Answers7

18

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
5

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;
skywall
  • 3,956
  • 1
  • 34
  • 52
2

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.

cooky451
  • 3,460
  • 1
  • 21
  • 39
2

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

Dacav
  • 13,590
  • 11
  • 60
  • 87
1

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;
}
RobM
  • 21
  • 1
  • Hi, This still gives me a unhandled exception. I'm shutting myself off from this method and will stick to the easy route. Thanks – Dan Mar 04 '12 at 13:42
  • Just figured out it was me that was causing the error after I fixed teh program. Much appreciate the help. – Dan Mar 04 '12 at 13:52
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.

rubenvb
  • 74,642
  • 33
  • 187
  • 332
  • Thanks for that. I still get the unhandled exception error from xstring file. Do you reckon visual studio is having a problem? I appreciate I shouldn't be doing this, I'll just walk away from it and stick to the basics of using string. – Dan Mar 04 '12 at 13:37
0

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
Mario
  • 35,726
  • 5
  • 62
  • 78