Hello Everyone,
I am trying to read the data from a file and store into a 2D array(the file contains 540000 values), but i m facing memory issues. Then my friend suggested to create a dynamic 2D array, i thought thats simple but when i searched for the code on web, i was in vain and hardly implement those stuff.
Can anyone please tell me how do i declare,intialize and access a 2D array dynamically.
The code which i tried to implement is below, but i am ending up in errors
[code]
#include #include int main()
{
FILE *fp; //file pointer for reading a file
double k;
char word[80];
double **DataLat=NULL;
DataLat=new double[360][1502]; // 2-D array for holding all the file values
int row=0, col=0; // row column and column declaration, used in 2-d array
fp = fopen("lat.txt", "r");
if ( fp == NULL )
{
puts("Unable to open the file");
exit(1); //terminate program
}
while(fscanf(fp,"%s",word)!=EOF)
{
k=atof(word);
DataLat[row][col]=k;
col++;
if(col==1502)
{
row++;
col=0;
}
if(row==359) exit(1);
}
delete []DataLat;
fclose( fp );
}
[/code]
thanks,
Kedar
Comments
[code]
double **DataLat=NULL;
DataLat=new double[360][1502]; // 2-D array for holding all the file values
[/code]
you can't allocate a 2d array like that. your compiler probably screemed very very loudly at you! It appears you want an array of doubles that has 360 rows, each row with 1502 double values.
You have a few options. Here is one.
[code]
double **DatLat;
DatLat = new double*[360];
for(int i = 0; i < 360; i++)
DatLat[i] = new double[1502];
[/code]
since this is a c++ program, you can use vectors. This is not a straight-forward 2d array, but relieves you from all the messy memory allocation stuff.
[code]
int main()
{
typedef vector COLS;
vector DatLat;
DatLat.resize(320);
for(int i = 0; i < 320; i++)
{
COLS& c = DatLat[i];
c.resize(1502);
}
}
[/code]
Here is a 3d method
[code]
int main()
{
double* DatLat[320];
// allocate the memory for the doubles in one
// huge 1d array
double* data = new double[320*1502];
// set pointers in the 2d array
for(int i = 0; i < 320; i++)
DataLat[i] = &data[i*1502];
//
//
// deallocate the array
delete[] data;
}
[/code]