c++ - why does the following code crash. (dynamic memory)? -


my program counts occurrence of each digit 0 9 in string. seems me have done correctly, problem still persists.

int main(){     string word = "23456745";     int* returnarray = count(word);      for(int =0; < 10; i++){         cout << << ": " <<  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 = 0 ; < length ; i++) {             char character = s[i];             int value = static_cast<int>(character -'0');             if(value == j)                 counter++;         }         array[j] = counter;         counter = 0;     }     return array; } 

int* array = new int(10); 

this creates 1 int value 10... 10 ints want [10] not (10). suggest put in...

std::cerr << "j " << j << '\n';  // add trace array[j] = counter; 

...and learn debug.

when you've got working, rewrite use std::vector - it's safer , more powerful approach.


Comments