Help please find the error in the code, after compiling and outputting the array to the screen - the program freezes and closes.

#include "stdafx.h" #include "conio.h" #include <locale.h> #include <stdlib.h> #include "stdio.h" int _tmain(int argc, _TCHAR* argv[]) { setlocale(LC_ALL, "Rus"); int n, m, i, j, flag, dop, g; printf("Введите размер матрицы\n"); scanf_s("%d %d", &n, &m); int **A; A = (int**)malloc(sizeof(int*)*n); for (i = 0; i<n; i++) { A[i] = (int*)malloc(sizeof(int)*m); printf("\n"); for (j = 0; j<m; j++) { A[i][j] = rand() % 100; printf("%6.1d ", A[i][j]); } } g = m; for (i = 1; i <= n; i = i + 2) { do { flag = 1; g--; for (j = 1; j <= m; j++) { if (A[i][j]>A[i][j + 1]) { dop = A[i][j]; A[i][j] = A[i][j + 1]; A[i][j + 1] = dop; flag = 0; } } } while (flag == 1); } for (i = 2; i <= n; i = i + 2) { do { flag = 1; g--; for (j = 1; j <= m; j++) { if (A[i][j]<A[i][j + 1]) { dop = A[i][j]; A[i][j] = A[i][j + 1]; A[i][j + 1] = dop; flag = 0; } } } while (flag == 1); } return 0; } 
  • You do not have C ++ code. You have a code in C. :) - Vlad from Moscow

2 answers 2

Classical error out of the array ...

You create A[n][m] , i.e. the first index is from 0 to n-1 inclusive, the second is from 0 to m-1 inclusive, and you address ...

For example, j<=m and appeal in general to A[i][j+1] - i.e. far beyond.

I didn’t look at the rest, but maybe there is something else ...

    If you have an array consisting of N elements, then the allowable range of indices for this array is [0, N-1]

    Thus, similar cycles like this one

     for (i = 2; i <= n; i = i + 2) ^^^^^^^ 

    are incorrect. Moreover, for example, in this cycle

      for (j = 1; j <= m; j++) { if (A[i][j]<A[i][j + 1]) { dop = A[i][j]; A[i][j] = A[i][j + 1]; ^^^^^^^ A[i][j + 1] = dop; flag = 0; } } 

    going beyond the valid range of indices, even if you write the condition of the cycle correctly

     for (j = 1; j < m; j++) ^^^^^ 

    And besides, you can have an infinite loop if the condition A[i][j]>A[i][j + 1] not fulfilled for any elements of the string.

      do { flag = 1; g--; for (j = 1; j <= m; j++) { if (A[i][j]>A[i][j + 1]) { dop = A[i][j]; A[i][j] = A[i][j + 1]; A[i][j + 1] = dop; flag = 0; } } } while (flag == 1);