The book Numerical recipes, 2nd edition (http://numerical.recipes) uses the following code to allocate/deallocate a memory for a vector v with subscripts [nl..nh]:
#define NR_END 1
#define FREE_ARG char*
float *vector(long nl, long nh)
/* allocate a float vector with subscript range v[nl..nh] */
{
float *v;
v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));
if (!v) nrerror("allocation failure in vector()");
return v-nl+NR_END;
}
void free_vector(float *v, long nl, long nh)
/* free a float vector allocated with vector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
Question 1: What is the purpose of adding/subtracting NR_END
elements?
Question 2: What is the purpose of converting float *
to char *
in free_vector
?
I understand that +1
in malloc
is due to the inclusive right boundary of the array (which is non-inclusive usually in C).