I want to write a program in C ++ that fills the lines of the two-dimensional array a and outputs this array line by line to the file output.txt . I use CodeBlocks. After starting the program, it does not stop, but is executed manually before the interruption, and the file "output.txt" quickly grows in size. When you open the file output.txt in Windows, the text editor does not respond. What's my mistake?

 #include <fstream> using namespace std; int main() { ofstream out; out.open("output.txt"); int a[5][5]; for (int i; i<4; ++i) { for (int j; j<4; ++j) { a[i][j]=j; } } for (int i; i<4; ++i) { for (int j; j<4; ++j) { out<<a[i][j]; out<<' '; } } out.close(); return 0; } 

    3 answers 3

    When creating variables, it is desirable to initialize them.

     for (int i = 0;i<4;i++){ for (int j = 0;j<4;j++){ a[i][j]=j; } } for (int i = 0;i<4;i++){ for (int j = 0;j<4;j++){ out<<a[i][j]; out<<' '; } } 

      I’ll draw your attention to the fact that when writing to the array a[i][j] = j and the incomprehensible values ​​of i and j other is much worse - you write to an incomprehensible place in memory. You are just unlucky that the program did not immediately crash out with an error cry (yes, this is luck; bad luck, when it as a result does not work correctly and gives incorrect results ...)

      • one
        Here, there would be size_t instead of int and there would be no record outside the array :) - Qwertiy
      • Hmm .. And how is it that the file grows? After all, if the condition for exiting the first external cycle is met, will it not go into the second? UPDATE: Itself understood: there variables are re-declared. - Qwertiy

      That's right, since you have an array of 5x5:

       for (int i = 0; i < 5; ++i){ for (int j = 0; j < 5; ++j){ 

      Since the initial values ​​of the variables i and j are not initialized, random values ​​are taken from the memory. As a result, not 25 values ​​are written, but MUCH more.