Thanks for the [
code] tags.
From just a quick glance (and no real study) line 16 is culprit for the OS errors.
int array[][COLS] = {0};
does not reserve any space in the data segment for the array. The compiler accepts it because it is technically valid syntax... but logically you must specify all dimensions in order to reserve space. (When compiling, make sure you turn on all warnings and your CC should complain about stuff like this.)
It looks like you want to have a variable sized array, so that your input file can be any size you like. You can do this strictly with arrays, but it is more grief than you probably want to spend. I suggest you use a
vector instead. Essentially it is an automatically managed, variable-length array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct record
{
int weight;
int cost;
};
void fillArray( vector <record> & table );
void printArray( const vector <record> & table );
int main()
{
vector <record> table;
fillArray( table );
printArray( table );
return 0;
}
void fillArray( vector <record> & table )
{
record data;
...
while (true)
{
// Skip the magic number at the beginning of the line
file.ignore( 256, ' ' );
// Get the data we want
file >> data.weight >> data.cost;
// We're done if we hit EOF or error
if (!file) break;
// Add the data to our array (vector)
table.push_back( data );
}
}
void printArray( const vector <record> & table )
{
for (unsigned n = 0; n < table.size(); n++)
{
cout << "Row " << (n+1) << "Col 1: "
<< table[ n ].weight << endl
...
}
}
|
Hopefully you can follow that OK.
I changed the record into named fields, but if you really want just a numbered array, you can do that too:
1 2 3 4 5
|
typedef int record[ 2 ];
...
file >> data[ 0 ] >> data[ 1 ];
...
cout << table[ n ][ 0 ] << endl;
|
[edit] Oh yeah, don't forget that array subscripts begin at zero.
Hope this helps.