So I am revisting some of my old code and I was creating 2D array dynamically in 2 different ways:
Code:
double **allocate_array(int row_dim, int col_dim){
double **result;
int i;
result=(double **)calloc(row_dim,sizeof(double *));
result[0]=(double *)calloc(row_dim*col_dim,sizeof(double));
for(i=1; i<row_dim; i++)
result[i]=result[i-1]+col_dim;
return result;
}
double **trainset;
trainset=allocate_array(5,5);
This way works fine but it appears I over dimensionalize it(I can access trainset[1][100]).
And its really weird what is going on here, creating a pointer to an x*y array in the first array cell and then pointers to the start of each "row". I have no idea how C resolves a 2D call i.e. trainset[1][1].
Also in the same program I used an inline method, that i tried putting into the allocate_array function instead of the first method:
Code:
double **allocate_array(int row_dim, int col_dim){
double **result;
int i;
result = (double **) calloc(row_dim,sizeof(double));
for(i=0;i<=row_dim;i++)
result[i]=(double *) calloc(col_dim,sizeof(double));
return result;
}
double **trainset;
trainset=allocate_array(5,5);
But again the dimensions are off as I can access trainset[1][10000], and seg fault only at like trainset[1][1000000].
Not sure if I should just ignore the over declaration and go with it, but its bugging me that I don't know what is going on. Its also strange that I can access trainset[5][1], which is the 6th and potentially non-existant, but its seg faults at trainset[6][1].