简体   繁体   English

C ++调试-从文件读取并输出2D数组

[英]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. 对于输入文件,第一行是4个数字:#rows #columns min-value max-value,我需要将它们打印出来并将整数放入第二行的二维数组中。 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. 这意味着,当一个元素等待插入数组但该数组已被填充到其预设容量时,您将分配一个更大的新内存块,将元素从原始数组复制到新数组,再加上新元素delete[]原始数组,并将其分配给新数组。

However, this requires memory management which in general is not a good practice in C++. 但是,这需要内存管理,这在C ++中通常不是一个好习惯。 The reason being that there are improvements like std::vector which is a wrapper around a dynamic array essentially the one described above. 原因是存在诸如std::vector类的改进,该改进实际上是对动态数组的封装,基本上是上述一种。 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. 但是因为您是一个初学者,所以我会说首先要学习使用低级内容的知识,然后再逐步提高。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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