在我的应用程序中,我创建了char*这样的:
class sample
{
public:
char *thread;
};
sample::sample()
{
thread = new char[10];
}
sample::~sample()
{
delete []thread;
}
Run Code Online (Sandbox Code Playgroud)
我在代码中做了正确的事吗?
kar*_*hik 13
需要注意的要点清单:
1)您需要为n个字符分配空间,其中n是字符串中的字符数,以及尾随空字节的空间.
2)然后,您将线程更改为指向其他字符串.因此,您必须使用delete[]函数来创建使用的变量new[].
但是你为什么要new和delete角色数据一起玩呢?为什么不使用std::string,而不是'C'功能?令人惊讶的是,为什么这么多人不做最简单的事情:
#include <cstdio>
#include <string>
int countWords(const char *p);
int main(int argc, char *argv[])
{
std::string pString = "The Quick Brown Fox!";
int numWords1 = countWords(pString.c_str());
printf("\n\n%d words are in the string %s", numWords1, pString.c_str());
int numWords2 = countWords(argv[1]);
printf("\n%d words are in the string %s", numWords2, argv[1]);
}
Run Code Online (Sandbox Code Playgroud)
无需new[],delete[],strcpy()等.
使用strlen().更好的是,不要使用char*和使用std::string字符串数据.