waz*_*eer -1 c++ memory dynamic
我的程序计算字符串中每个数字从0到9的出现次数.在我看来,我已经完成了所有事情,但问题仍然存在.
int main(){
string word = "23456745";
int* ReturnArray = count(word);
for(int i =0; i < 10; i++){
cout << i << ": " << ReturnArray[i] << " \n";
}
delete [] ReturnArray;
return 0;
}
int* count(const string& s){
int length = s.length();
int* array = new int(10);
int counter =0;
for(int j = 0 ; j < 10 ; j++) {
for(int i = 0 ; i < length ; i++) {
char character = s[i];
int value = static_cast<int>(character -'0');
if(value == j)
counter++;
}
array[j] = counter;
counter = 0;
}
return array;
}
Run Code Online (Sandbox Code Playgroud)
int* array = new int(10);
Run Code Online (Sandbox Code Playgroud)
这会创建一个值为10的int ...,[10]而不是10个int (10).然后我建议你投入......
std::cerr << "j " << j << '\n'; // add some trace
array[j] = counter;
Run Code Online (Sandbox Code Playgroud)
...并学习调试.
当你有它工作,重写它使用std::vector- 它是一个更安全和更强大的方法.