在c++中以这种方式创建字符串数组是否正确?

Is it correct to create array of strings this way in c++?

本文关键字:数组 字符串 是否 创建 方式 c++      更新时间:2023-10-16

在c++中以这种方式创建n字符串s的数组是否正确?

string *a = (string*)malloc(sizeof(string)*n);
...
free(a);

不,这是错误的。malloc不调用std::string的构造函数,malloc所做的只是分配内存并使内存未初始化。至少您会想要使用new。但是,创建字符串数组的最佳方法是使用std::vector:

std::vector<std::string> a(n);

现在你再也不用担心内存管理了

No。你的字符串从来没有真正被构造过。不像new, malloc()不构造对象——它只是分配内存。

就用这个:

  std::string a[n];

  std::vector<std::string> a;

因为c++字符串内部会动态分配内存来保存字符,所以std::string的sizeof通常非常小(可能是16字节),不管包含多少字符。因此(不像C语言,字符串处理经常涉及大量的malloc/free噩梦),通常不需要动态分配字符串。

Try

string *a = new string[SIZE];

释放它:

delete [] a;

如果不使用指针的话,会容易得多:

string a[n];

无需删除