Work with a two-dimensional array. The code works correctly. Here is a problem piece. What am I doing wrong?

void delete_array(int **array, int row_count){ for(int r=0; r<row_count; r++) delete[] array[r]; delete [] array; } int **create_array(int n,int m){ int** array=new int*[m-1]; for(int s=0;s<m;s++) array[s]=new int [1]; return array; } main(){ int **array; //Тут читаем n и m из файла array = create_array(n,m); delete_array(m); } 

Programmulina crashes. The compiler does not complain (gcc).

    2 answers 2

    Of course she will fly out. delete_array requires two parameters, and you pass one. That is, at least you need to call

     delete_array(array, m); 

    it's also very strange that gcc missed main() . Is he terribly ancient? or you are compiling not a plus code, but a clean one (although there is a new one).

    The second mistake was hidden in a prominent place. when an array is created, its first dimension is m-1 . And when you delete (and when you create), we go through one more element. Since we go beyond the limits of the array, then there are no problems.

    Corrected version

     void delete_array(int **array, int row_count) { for(int r=0; r<row_count; r++) delete[] array[r]; delete [] array; } int **create_array(int n,int m) { int** array=new int*[m]; for(int s=0; s<m; s++) array[s]=new int [1]; return array; } int main() { int **array; //Тут читаем n и m из файла int m = 10; int n = 10; array = create_array(n,m); delete_array(array, m); return 0; } 
    • Fine. Thank you so much. I didn’t even think that I was singling out something wrong. And the second is that I do not pass the array itself to the delete_array function — it was an accident, I didn’t copy it. - 0x0718

    If I'm not mistaken, delete [] array; - you need to specify once in a function to remove an array of pointers. And in the loop, you delete all array pointers.

    • @Infum, this (deletion in a loop) is just right. You would have already read the answer given to @KoVadim. - avp