为什么此代码错误?我缺少有关的行为的东西delete
和delete[]
?
void remove_stopwords(char** strings, int* length)
{
char** strings_new = new char*[*length];
int length_new = 0;
for(int i=0; i<*length; i++) {
if(is_common_keyword(strings[i]) == 0) {
strings_new[length_new] = strings[i];
length_new++;
}
else {
delete strings[i];
strings[i] = nullptr;
}
}
delete[] strings;
strings = new char*[length_new];
for(int i=0; i<length_new; i++) {
strings[i] = strings_new[i];
}
delete[] strings_new;
*length = length_new;
}
说明:此代码应采用C样式字符串的数组,并删除其中的某些特定字符串;C样式字符串数组是使用new []创建的,每个C样式字符串都是使用new创建的。代码的结果是没有单词被取消,但仅对数组进行了切片。
我看不到使用new[]
或delete[]
显示的代码有任何问题。
不,等等
我看到了很多问题,但是您的意图很明确,并且代码似乎可以完成您想要的事情。
我注意到的唯一逻辑问题是您要按strings
值传递(它是a char**
,并且在函数中重新分配它不会影响包含指针的调用者变量)。将签名更改为
void remove_stopwords(char**& strings, int* length)
因此,应传递引用来解决该问题。
(1)使用std::vector<const char *>
似乎更合乎逻辑,甚至更好(std::vector<std::string>
如果可能的话),它将处理所有分配和释放。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句