在c++中以这种方式创建字符串数组是否正确?
Is it correct to create array of strings this way in c++?
在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];
无需删除
相关文章:
- 使用 jsoncpp 解析 json 数组字符串
- C++ 对象数组字符串输入在控制台上不起作用
- 插入了 C++ 数组字符串数据,但在显示输出时不显示
- 无法区分 JSON 对象/数组/字符串
- 为什么数组(字符串类型)的大小是 24 字节,带有单个空格元素
- 如何使用数组字符串进行输入验证
- (C++) 打印字符数组字符串的单词时出现问题
- 使用Back_inserter从任何位置的输入字符中使用Back_inserter进行过滤数组字符串
- C 函数反转字符数组字符串
- 如何在 c++ 中创建数组(字符串 [] )的向量
- 如何返回数组字符串的指针
- char数组字符串混淆
- 如何从字符数组字符串中提取空格
- 是否可以将 Bitset<8> 的值复制到数组字符串而不转换它们?
- C++数组字符串函数
- 如何在函数中操作字符数组(字符串)的指针,该指针在C / C ++中作为参数传递
- visual将音频文件存储到数组/字符串流C++中
- c++在char数组(字符串)上将what替换为
- 将数组字符串转换为intger c++(初学者)
- 需要设置数组字符串长度,使其恰好为13