C++ 字符串和指针
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9554812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ strings and pointers
提问by Dan
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)?
有人可以通过仍然使用指针和字符串而不是字符数组(我已经知道如何做)来提出解决方案吗?
回答by dasblinkenlight
This is because you have not allocateyour 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.
值得补充的是,在这种情况下使用指针是毫无意义的:标准 C++ 库中的字符串对象从堆中为字符串分配数据;无论如何,字符串通常不过是一对指针。
回答by skywall
I think, you don't want to use pointers
at all. You can work with strings
without pointers.
我想,你根本不想使用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;
回答by cooky451
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.
但是真的没有理由这样做,只需在堆栈上定义一个普通的字符串变量即可。
回答by Dacav
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).
您实际上可以使用指向字符串的指针,但它们旨在用作本地对象并作为引用(或常量引用,如果您愿意)传递。
回答by RobM
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;
}
回答by rubenvb
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.
请注意,在这些简单的情况下使用指针是在打击自己,无论是在语法方面还是在错误方面。
EDITI 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 上运行。
回答by Mario
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:
阅读c 编程的10 条戒律。对于今天的开发人员来说,有些或多或少已经过时了,但有些仍然很重要,例如第二个:
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