int nrow=5,ncol=7,i,j;
float **ptr;
/*allocation*/
ptr=(float **) malloc(nrow*sizeof(float*));
ptr[0]=(float *) malloc(nrow*ncol*sizeof(float));
/*initialize*/
for (i=0;i<nrow;i++)
for (j=0;j<ncol;j++) ptr[i][j]=0.0;
We know in the above case, the row starts from 0
and ends in nrow-1
, the column starts from 0
and ends in ncol-1
. But how can I let the row start from -4
and end in nrow+3
, also let the column start from -4
and end in ncol+3
?
Supplementary code:
#include <stdio.h>
#include <stdlib.h>
float *vector(int nl, int nh){
/* allocate a float vector with subscript range v[nl..nh] and initializing
this vector, eg. vector[nl..nh]=0.0 */
float *v;
int i,NR_END=0;
v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));
for (i=0;i<(nh-nl+1+NR_END);i++) v[i]=0.0;
return v-nl+NR_END;
}
int main(int argc, char *argv[])
{
int i,nrow=5, row1, row2;
float *v;
row1=-4;
row2=nrow+3;
v = vector(row1,row2);
for (i=-4;i<(nrow+4);i++) {
v[i]=(float)i;
printf("v[%d]=%f\n",i,v[i]);
}
exit(0);
}
If I run the above code, it'll get the correct answer:
v[-4]=-4.000000
v[-3]=-3.000000
v[-2]=-2.000000
v[-1]=-1.000000
v[0]=0.000000
v[1]=1.000000
v[2]=2.000000
v[3]=3.000000
v[4]=4.000000
v[5]=5.000000
v[6]=6.000000
v[7]=7.000000
v[8]=8.000000