use*_*248 1 c++ arrays new-operator delete-operator
为什么这段代码错了?我缺少有关的行为的东西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;
}
Run Code Online (Sandbox Code Playgroud)
解释:这段代码应该采用一系列C风格的字符串并删除它们的一些特定字符串; 使用new []创建C样式字符串数组,并使用new创建每个C样式字符串.代码的结果是没有单词被取消,但数组只是被切片.
我在使用new[]或delete[]显示的代码中没有看到任何问题.
不,等等.
我看到很多问题,但你的意图很明确,代码似乎正在做你想做的事情.
我注意到的唯一逻辑问题是你strings通过值传递(它是a char**并且在函数中重新分配它不会影响包含指针的调用者变量).将签名更改为
void remove_stopwords(char**& strings, int* length)
Run Code Online (Sandbox Code Playgroud)
所以传递一个引用而不是修复它.
(1)使用std::vector<const char *>似乎更合乎逻辑,std::vector<std::string>如果可能的话更好,它将负责所有分配和解除分配.
| 归档时间: |
|
| 查看次数: |
113 次 |
| 最近记录: |