2020-04-13

Why can't std::string* pstr; be used to hold a string in C++ while only std::string str; can?

Look at this code:

#include <iostream>
#include <string>
int main(void) {
        std::string str;
        std::cout << "Please enter string:" << std::endl;
        std::cin >> str;
        std::cout << str << std::endl;

        return 0;
}

It works fine.

Now I want to experiment with pointer to string.


#include <iostream>
#include <string>
int main(void) {
        std::string* pstr;
        std::cout << "Please enter string:" << std::endl;
        std::cin >> *pstr;
        std::cout << *pstr << std::endl;

        return 0;
}


It compiles and runs.

But after I type something and enter, the error message appears

Segmentation fault  (core dumped) ./a.out

I have no idea why.

Why can't std::string* pstr; be used to hold a string in C++ while only std::string str; can? 

No comments:

How to Add a Directory to PATH in Linux

 https://linuxize.com/post/how-to-add-directory-to-path-in-linux/ When you type a command on the command line, you’re basically telling the ...