这是正确的还是有更好的方法来做到这一点。
Visual给出了一个错误:“strcpy()是折旧”。
using namespace std;
char* ptr;
ptr=(char *)calloc(1,sizeof(char));
cout << "Input the equation." << endl;
string eqn;
getline(cin, eqn);
ptr = (char *)realloc(ptr, top + eqn.size()+1);
strcpy(ptr, eqn.c_str());我想要ptr是输入方程的精确大小。
发布于 2014-09-13 16:38:55
假设您想要实现的是在给定一个modifiable的情况下创建一个std::string char缓冲区,那么更好的选择是使用std::vector<char>来创建这样一个缓冲区。
#include <vector>
#include <string>
#include <iostream>
//...
void foo(char *x)
{
// do something to 'x'
}
using namespace std;
int main()
{
cout << "Input the equation." << endl;
string eqn;
getline(cin, eqn);
// construct vector with string
std::vector<char> ptr(eqn.begin(), eqn.end());
// add null terminator
ptr.push_back(0);
foo( &ptr[0] );
}上面的代码通过使用名为std::vector的ptr创建一个可修改的、以空结尾的C字符串.请注意,没有对malloc、calloc等的调用。
发布于 2014-09-13 16:13:26
不推荐strcpy,因为它是缓冲区溢出问题的一个常见来源,通常是用strncpy修复的。尽管如此,首先使用std::string要好得多。
发布于 2014-09-13 16:57:47
如果您希望使用malloc复制字符串,则只需使用strdup即可。
char* ptr = strdup(eqn.c_str());
// ..
free(ptr);https://stackoverflow.com/questions/25825076
复制相似问题