Hi All,
I have been using C for a while, still haven't got around with pointers
I am defining a pointer (to a pointer) **v; in main.
Then **v is passed to a function Initialise() to assign values.
Initialise() calls dmatrix() to allocates memory to v.
Finally, the function finalise(v) frees the memory.
PROBLEM: Even though v is passed as a reference (via pointer), its values are not accessible to the main function.The program fails when tries to free the memory.
I have multiple variables that need to be initialised in this fashion.
Can anyone offer any clues or workarounds.
Thanks very much in advance for your help.
Code:
#include <stdio.h>
#include <stdlib.h>
void Initialise(double **v, int row, int column, int value);
void finalise(double **v);
double **dmatrix(int row, int column);
void freedmatrix(double **a);
main(){
double **v;
Initialise(v,10,10,3);
printf("v from main %f\n",v[1][1]);
finalise(v);
}
void Initialise(double **v, int row, int column, int value){
int i,j;
v=dmatrix(row+1,column+1);
for (i=1;i<=row;i++){
for (j=1;j<=column;j++){
v[i][j]=value;}}
printf("v from function Initialise %f\n",v[1][1]);
}
void finalise(double **v){
freedmatrix(v);}
double **dmatrix(int row, int column){
int i;
double **a;
a=(double **) malloc((row)*sizeof(double *));
a[0]= (double *) malloc((row)*(column)*sizeof(double));
for(i=1;i<=(row-1);i++){
a[i]=a[i-1]+column;
}
return(a);
}
void freedmatrix(double **a){
free(a[0]);
free(a);
}