This is my suggestion on your program:
Code:
/* Array2D.c: Shows how to malloc 2D arrays of type int and double,
by Adak, March 2009.
Status: ok
This is what the data file should have in it:
ELEMENTS
1 2 4 3 1
2 5 7 4 2
3 4 8 6 3
4 7 9 8 4
END_ELEMENTS
COORDINATES
1 0.000000 10.000000 0
2 0.000000 5.000000 1
3 5.000000 10.000000 2
4 5.000000 5.000000 3
5 0.000000 0.000000 4
6 10.000000 10.000000 5
7 5.000000 0.000000 6
8 10.000000 5.000000 7
9 10.000000 0.000000 8
END_COORDINATES
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void) {
FILE * msh_file_ID;
//Testing the code:
int i, k, num;
int nnodes = 9;
int nelem = 4;
double garbage = 0.00; //used to force linking to floating point header
char header[32];
int **CONN; //2 *'s for a 2D array
double **COORDS;
garbage = sqrt(4); //force the floating pt packing to load up
CONN = malloc(nelem * sizeof(int*)); //get memory for 1D
for (i = 0; i < nelem; i++) {
CONN[i] = malloc(4 * sizeof(int)); //get memory for 2D
}
COORDS = malloc(nnodes * sizeof(double*));
for(i = 0; i < nnodes; i++)
COORDS[i] = malloc(2 * sizeof(double));
msh_file_ID = fopen("Array2D.txt", "rt");
//READ the FIRST LINE OF THE FILE: ELEMENTS
fscanf(msh_file_ID, "%s\n", header);
printf("%s\t\n", header);
i = 0;
while( !feof(msh_file_ID)){
for(k = 0; k < nelem; k++) {
//Read CONN:
fscanf(msh_file_ID, "%d %d %d %d %d\n",&(CONN[k][0]),&(CONN[k][1]),&(CONN[k][2]),&(CONN[k][3]));
printf(" %d %d %d %d %d\n ", CONN[k][0], CONN[k][1], CONN[k][2], CONN[k][3]);
}
//Read the intermediate strings: "END_ELEMENTS" and "COORDINATES"
//String END_ELEMENTS
fscanf(msh_file_ID, "%s\n", header);
printf("%s\t\n", header);
//String COORDINATES
fscanf(msh_file_ID, "%s\n", header);
printf("%s\t\n", header);
//Read COORDS
for(i = 0; i < nnodes; i++) {
fscanf(msh_file_ID, "%d", &num);
fscanf(msh_file_ID, "%lf %lf", &COORDS[i][0], &COORDS[i][1]);
printf(" %d. %lf %lf\n", num, COORDS[i][0], COORDS[i][1]);
}
fscanf(msh_file_ID, "%s", header);
printf("%s\n", header);
//if(strcmp(header, "END_COORDINATES") == 0) //just FYI
//break;
}//END while
fclose(msh_file_ID);
printf("\n\n\t\t\t press enter when ready \n");
garbage = getchar(); garbage++;
for (i = 0; i < nelem; i++)
free(CONN[i]);
free(CONN);
for(i = 0; i < 9; i++)
free(COORDS[i]);
free(COORDS);
return 0;
}
The if() else() type logic, I didn't like. It made it lean toward being unclear and harder to debug.
I briefly tested the !feof() loop, and found it worked ok in your loop, so I didn't replace it.
Cheers!