wca*_*ale -2 c++ memory free char
如何使用这样的东西释放内存(Visual Studio 2008 - Win32/console):
我只能包括:iostream
#include <iostream>
void data_t(char *test[])
{
test[0] = new char[];
test[1] = new char[];
test[0] = "Test1";
test[1] = "Test2";
}
int main()
{
char *test[2];
data_t(test);
cout<<test[0]<<"\n";
cout<<test[1]<<"\n";
delete[] test[0];//Debug assertion failed! - The program '[7884] Zadanie_4_sortowanie.exe: Native' has exited with code 3 (0x3).
delete[] test[1];
}
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
char[]是一个不完整的类型,不能在new表达式中使用.您需要实际决定数组大小,例如:
char * p = new char[200];
Run Code Online (Sandbox Code Playgroud)
然后你可以说你什么delete[] p;时候完成.
你会需要像strcpy将数据复制到的char数组.您编写的分配仅覆盖指针,从而失去对动态分配(即泄漏)的跟踪.(事实上,如果你只是想要修复字符串,你可能根本不需要动态分配,所以只需删除带有new和的行delete.)
但是,你真正想要的是std::array<std::string, 2>:
#include <array>
#include <string>
#include <iostream>
std::array<std::string, 2> test = { "Test1", "Test2" };
std::cout << test[0] << "\n" << test[1] << "\n";
Run Code Online (Sandbox Code Playgroud)
或通过引用传递:
void populate(std::array<std::string, 2> & a)
{
a[0] = "Test1";
a[1] = "Test2";
}
int main()
{
std::array<std::string, 2> test;
populate(test);
// print ...
}
Run Code Online (Sandbox Code Playgroud)
test [0]包含一个指向静态字符串"Test1"的指针,该指针无法解除分配.使用strcpy复制C字符串.
| 归档时间: |
|
| 查看次数: |
9225 次 |
| 最近记录: |