使用Malloc创建一个动态向量数组



你好,我正在尝试学习c++,我试图使用malloc来创建一个向量数组,但我似乎无法让它工作。向量包含字符串。我没有问题,使数组与整数,但使用向量给我带来了一些问题。我在使用realloc时有同样的问题。

我正在尝试这个,我做错了什么?

int buffer_size = 3;
int buffer_count= 0;
vector * words = (string *) malloc(buffer_size * sizeof(string));
//As array of vectors fills up I will add to the buffer count
if(buffer_count => buffer_size){
words = (string*) realloc(words,buffer_size * sizeof(string));
}

就像我说的,我一定是在malloc或realloc函数中出现了一些问题,我所尝试的一切都给出了各种错误,例如"使用类模板'vector'需要模板参数。

谢谢你的帮助。

std::vector和其他STL容器旨在消除使用指针和动态内存分配所引起的复杂性,例如内存泄漏,访问越界数据时调用的未定义行为等。

std::vector本身是动态的。emplace_backpush_back越多,它就越生长。如果你想要一个包含可变长度字符串的vector,为什么不这样声明呢:

std::vector<String> words {"Hello", "World"};
类似地,您可以创建多维向量:
std::vector<std::vector<Type>> doubleContainer {};

std::vector是一个模板类,但是您试图在不为其模板参数指定任何值的情况下使用它。这就是为什么你得到错误。

然而,你不能把string*指针赋值给vector*指针,就像你想做的那样。您的words变量需要声明为string*。至少这样代码就可以编译了。

然而,代码在运行时不能正常运行,因为malloc()/realloc()函数来自C运行时库,但std::string是一个需要构造的c++非平凡类,并且C函数不调用类构造函数。因此,您将不得不使用placement-new来解决这个问题(忘记使用realloc(),因为没有安全的方法来realloc内存,也是place_new 'ed),例如:

string *words = (string*) malloc(buffer_size * sizeof(string));
for (int i = 0; i < buffer_size; ++i) {
new(&words[i]) string;
}
...
if (buffer_count >= buffer_size) {
int new_buffer_size = buffer_size * 2;
string *new_words = (string*) malloc(new_buffer_size * sizeof(string));
for (int i = 0; i < buffer_size; ++i) {
new(&new_words[i]) string(words[i]);
}
for (int i = buffer_size; i < new_buffer_size; ++i) {
new(&new_words[i]) string();
}
for (int i = 0; i < buffer_size; ++i) {
words[i].~string();
}
free(words);
words = new_words;
buffer_size = new_buffer_size;
}
...
for (int i = 0; i < buffer_size; ++i) {
words[i].~string();
}
free(words);

在这种情况下,使用new[]/delete[]会更好/更安全:

string * words = new string[buffer_size];
...
if (buffer_count >= buffer_size) {
int new_buffer_size = buffer_size * 2;
string *new_words = new string[new_buffer_size];
for (int i = 0; i < buffer_size; ++i) {
new_words[i] = words[i];
}
delete[] words;
words = new_words;
buffer_size = new_buffer_size;
}
...
delete[] words;

或者,正确地使用std::vector,让它为你处理所有的动态内存管理:

vector<string> words;

您正在使用malloc为字符串向量分配内存,但是malloc只分配原始内存,这意味着您不能直接使用它来创建向量数组。相反,您需要使用new关键字。

vector<string> *words = new vector<string>[buffer_size];

您试图将malloc的返回值强制转换为向量*,但这是不允许的。相反,您可以使用vector类的reserve方法为数组中的vector分配必要的内存量,然后使用emplace_back方法向数组中添加新元素。

if (buffer_count >= buffer_size) {
words->reserve(buffer_size * 2);
words->emplace_back();
}

希望这对你有帮助!