Thanks everyone for the help, however still no luck with the dynamic allocation.
This is the current program
Code:
#define TRUE = 1
#include <stdio.h>
#include <math.h>
main()
{ char filename[100];
FILE *inputfile;
int row, col, i, j, k, l;
char* formatstring;
float** datapoint;
/*information*/
printf("Please enter the name of the input file (enter exit for termination): ");
while(1==1)
{
scanf("%s", filename);
inputfile = fopen(filename, "r" );
if (filename != NULL)/*file open without error*/
{
if (filename == "exit") exit(0);
if (inputfile == 0) /*file not found*/
{
printf("file not found"); exit(0);
}
else
{
printf("file opened\n");
fscanf(inputfile, "%d, %d", &row, &col); /*read from input file number of rows and colums*/
printf("%d rows and %d columns of data will be read\n", row, col);
formatstring = (char*) malloc(col * 4 - 2); /*allocate string array for format string*/
formatstring[0] = '%'; /*create the "%d, %d, %d, %d, ........%d" */
formatstring[1] = 'd';
i = 0;
do
{
formatstring[i*4+2] = ',';
formatstring[i*4+3] = ' ';
formatstring[i*4+4] = '%';
formatstring[i*4+5] = 'd';
i++;
}
while (i < col - 1);
/*allocate 2d array*/
allocate2D(datapoint, row, col);
for (i = 0; i < 13; i++)
{
for (j = 0; j < 14; j++)
{
datapoint[i][j] = (float) i + j; /*assignment*/
printf("%d\n", datapoint[i][j]); /*debug*/
}
}
for (i = 0; i < 13; i++)
{
for (j = 0; j < 14; j++)
{
printf("%d, %d, %d\n", datapoint[i][j] ,i , j);
}
}
break;
}
}
else /*file opern error*/
{
printf("error when opening file! program abort"); exit(0);
}
}
free (datapoint);
}
allocate2D(array, nrows, ncols)
float** array;
int nrows;
int ncols;
{
/* allocate array of pointers */
array = (float**)malloc(nrows*sizeof(float*));
/* allocate each row */
int i;
for(i = 0; i < nrows; i++) {
array[i] = (float*)malloc(ncols*sizeof(float));
}
}
though the allocate array function went through without problem, problem occurs whenever I try to assign any value to the array in the line /*assignment*/ and /*debug*/, program just terminates there stating "program.exe stopped working". The Visual studio debugger seems to indicate an access violation error, I think it has everything to do with the dynamic array allocation.
I get the idea that a 2d array is an array of pointers, of which each pointer is on its own an array, increasing dimension of the array should work the same way. However I just cannot get it to work