简体   繁体   中英

C++ debugs - read from a file and output the 2D array

#include<iostream>
#include<fstream>
using namespace std;


int main(){
      ifstream infile;
      int X,Y;
      char ch;
      infile.open("input.txt");
      int** intarray = new int*[X];
      for(int i = 0; i < X; ++i)
       intarray[i] = new int[Y];
           for(int k=0; k<16; ++k){
             for(int j=0; j<24; ++j){
              infile >> intarray[k][j];
              cout << intarray[k][j]<<" ";
             }
           cout<< endl;
           }

           infile.get(ch);

  infile.close();

}

Here is what I have wrote so far, the array is declared dynamically but when I run, it comes out error saying Segmentation fault (core dumped). for the input file, first line is 4 numbers: #rows #columns min-value max-value, I need to print them out and put integers into the 2-d array starting second line. How can I do that?

Usually you'd start with a prealloated array of a certain size, then increase the capacity as more elements are inserted. This means when an element is pending insertion to the array but the array is filled to its preset capacity, you allocate a new, larger block of memory, copy the elements from the original array to the new array, plus the new element, delete[] the original array and assign it to the new array.

However, this requires memory management which in general is not a good practice in C++. The reason being that there are improvements like std::vector which is a wrapper around a dynamic array essentially the one described above. But because you are a beginner, I would say develop the knowledge of working with the low-level stuff first, then work your way up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM