Solved

# adding an integer to a pointer while creating it (pointer).

Posted on 2006-04-10

Can someone please explain me what the folowing code is doing ? I have a problem at , why the pointer is being subtracted from the initial value while returning it. What does it achieve ? And the same (being added) while freeing it.

/*

* Allocates memory for an double vector from [beg...end]

*/

double *Dec_Vector(int beg, int end)

{

double *vec;

if( (end - beg +1) <= 0)

{printf("In Dec_Vector, Chk the parameters\n");exit(1); }

vec = (double *)malloc((end-beg+1)*sizeof(double));

if (vec == NULL) Abort("Error allocating memory in Dec_vector, Aborting ...\n");

return(vec-beg);

}

/*

* Free a dec vector

*/

void Free_Dec(double *vec, int beg, int end)

{

free(vec+beg);

}

For a 2D array ....

/*

* Allocate memory for a double matrix [begrow...endrow][begcol...endcol]

*/

double **Dec_Matrix(int begrow, int endrow, int begcol, int endcol)

{

double **mat;

int i;

mat = (double **)malloc( (endrow-begrow+1)*sizeof(double*));

if (mat == NULL) Abort("Error allocating memory in Dec_Matrix, Aborting ...\n");

mat -= begrow;

for (i=begrow; i<=endrow; i++)

{

mat[i] = (double *)malloc((endcol-begcol+1)*sizeof(double));

if (mat[i] == NULL) Abort("Error allocating memory in Dec_Matrix, Aborting ...\n");

mat[i] -= begcol;

}

return(mat);

}

/*

* Free a Dec matrix

*/

void Free_Decmatrix(double **mat, int begrow, int endrow, int begcol, int endcol)

{

int i;

for(i=begrow; i<=endrow; i++)

free(mat[i]+begcol);

free(mat+begrow);

}

And the array is referenced in the main program as below with their starting int values....

*aa = Dec_Matrix(1,nclone,0,nprobe);

for (i=1; i<=nclone; i++)

for (j=0; j<=nprobe; j++)

----- here goes some code

I dont understand that why not just return the array without subtracting and indices references be just from 0 to its length...

thanks a lot for explaing this code snippet ..

Susanta