I created two dynamic arrays, two-dimensional and one-dimensional (arrA [n] [m] and arrB [n]). Help me find an error in the loop. In some lines it finds the maximum element, in others it finds garbage.

int maxv = A - 1, nextv; // A - ΠΌΠΈΠ½ΠΈΠΌΠ°Π»ΡŒΠ½Ρ‹ΠΉ Π²ΠΎΠ·ΠΌΠΎΠΆΠ½Ρ‹ΠΉ элСмСнт массива ΠΏΡ€ΠΈ Π³Π΅Π½Π΅Ρ€Π°Ρ†ΠΈΠΈ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (maxv < (nextv = arrA[i][j])) { maxv = nextv; arrB[i] = maxv; } } } 

    3 answers 3

    After you have found the maximum element in the line, it remains in maxv ... This variable must be initialized for each line:

     int maxv = A - 1, nextv; // A - ΠΌΠΈΠ½ΠΈΠΌΠ°Π»ΡŒΠ½Ρ‹ΠΉ Π²ΠΎΠ·ΠΌΠΎΠΆΠ½Ρ‹ΠΉ элСмСнт массива ΠΏΡ€ΠΈ Π³Π΅Π½Π΅Ρ€Π°Ρ†ΠΈΠΈ for (int i = 0; i < n; i++) { maxv = A - 1; for (int j = 0; j < m; j++) { if (maxv < (nextv = arrA[i][j])) { maxv = nextv; arrB[i] = maxv; } } } 

    But you can do without this variable at all :)

      Actually, this should be a comment, but so far I am not allowed (not enough rating) to leave them.

      Your problem is that you do not reset maxv before entering the internal loop, unless of course I correctly understood the task.

        Generally for such things there is a debugger. But here is the corrected version:

         int maxv = A - 1, nextv; // На самом Π΄Π΅Π»Π΅ эти ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½Ρ‹Π΅ Π½Π΅ Π½ΡƒΠΆΠ½Ρ‹ for (int i = 0; i < n; i++) { arrB[i] = arrA[i][0]; for (int j = 1; j < m; j++) { if (arrB[i] < arrA[i][j]) { arrB[i] = arrA[i][j]; } } } 

        There is no need to use additional variables.