Hi,
I have a very simple program that reads
a file line by line and stores each line in a 2-d array.
The program complies without error and runs correctly
when I use a small test file (that it reads from),
but when I use a larger file (has 300,000 lines instead of 2,000)
the program says segmentation fault when I run the executable.
It still compiles without error though.
How can this happen, if the only difference is the number of rows in the files.
Thank you!
#include <iostream>
#include <fstream>
#include <string>
/**
The first line of the file being read contains two numbers,
the number of rows and the number of columns,
of a matrix that appears in the subsequent lines.
The program stores the matrix as a 2-d array
called "arr", and then prints the array to the screen.
The file contains e.g.,
2 3
2.1 7 12
8 3 0.1
**/
usingnamespace std;
int main()
{
ifstream file("check.txt");
if(!file.is_open())
{
cout << "Error opening file." << endl;
return -1;
}
int numRows, numCols;
file >> numRows >> numCols;
double arr[numRows][numCols];
// read each value into the array
for(int i = 0; i < numRows; i++)
{
for(int j = 0; j < numCols; j++)
{
file >> arr[i][j];
}
}
file.close();
for( int i = 0; i < numRows; i++ )
{
for( int j = 0; j < numCols; j++ )
{
cout << arr[i][j] << " ";
}
cout << endl;
}
> The program complies without error
After adding the missing brace in line 57
$ g++ foo.cpp -pedantic-errors
foo.cpp: In function ‘int main()’:
foo.cpp:34:29: error: ISO C++ forbids variable length array ‘arr’ [-Wvla]
foo.cpp:34:29: error: ISO C++ forbids variable length array ‘arr’ [-Wvla]