Thank you very much for your help. As a service to the community, and should anyone else ever be in the same situation as me, I have posted some working code below. I have also for completeness added a way to destroy the 2D arrays again thus preventing memory leaks. Constructive criticism is welcome
Code:
#include <stdio.h>
#include <stdlib.h>
#define MAXCOLS 2 //Defines the maximum number of columns in the 2D array
int dataini(double*** data); //reads data
double** make2Darr(int nrows, int ncols); //Allocates memory
void unmake2Darr(double** arr, int nrows); //Frees memory from 2D array
void print2Darr(double** arr, int nrows, int ncols, FILE *fpt); //Prints 2D array to filestream fpt (for example stdout)
int main()
{
double** data=NULL; //"Data Matrix": 2D array that eventually will hold the data
int nrows=dataini(&data); //Initialises the data to the data matrix above. Returns the number of rows (needed for printing and deleting)
fprintf(stdout,"Printing data array in main:\n");
print2Darr(data, nrows,MAXCOLS, stdout); //Prints the data matrix
unmake2Darr(data,nrows); //Frees up the memory allocated to the data matrix. Not really needed since main is about to end anyway
printf("Press any key to end\n");
getchar();
return 0;
}
Functions used:
Code:
int dataini(double*** data_arr) //Takes the memory adress to the data array
{
long maxrows=2; //maximum 2 rows. Can be determined during runtime if needed.
double** data; //This is what will eventually be the data matrix
data=make2Darr(maxrows,MAXCOLS);
int row, col;
for(row=0;row<maxrows;row++)
{
for(col = 0; col < MAXCOLS; col++)
{
data[row][col] = 2*row+col; //Sets the data matrix to some arbitrary values. The values have here been chosen so the data matrix will be [0,1;2,3]
}
}
fprintf(stdout,"Printing data array:\n");
print2Darr(data, maxrows,MAXCOLS, stdout); //Prints the data matrix. Compare with the print from main. Should be the same
fprintf(stdout,"Returning to main\n");
fprintf(stdout,"\n");
*data_arr=data; //The data matrix is now fully created
return maxrows;
}
double** make2Darr(int nrows, int ncols)
{
double** arr;
arr=calloc(nrows,sizeof(double *)); //Type double**. Notice: Unneccesary to do cast from calloc. Doing so would only supress some warnings if any
int i=0;
if(arr==NULL)
{
perror("Failed to allocate memory\n");
exit(EXIT_FAILURE);
}
for(i = 0; i < nrows; i++)
{
arr[i] = calloc(ncols , sizeof(double)); //Type double*
if(arr[i]==NULL)
{
perror("Failed to allocate memory\n");
exit(EXIT_FAILURE);
}
}
return arr;
}
void print2Darr(double** arr, int nrows, int ncols, FILE *fpt)
{
int i,j;
for(i=0;i<nrows;i++)
{
for(j=0;j<ncols;j++)
{
fprintf(fpt,"%f\t", arr[i][j]);
}
fprintf(fpt,"\n");
}
}
void unmake2Darr(double** arr, int nrows)
{
int i=0;
for(i=0;i<nrows;i++)
{
free(arr[i]);
}
free(arr);
}