Question??: NR in C


nge
03-31-2003, 10:33 AM
#define NR_END 1
...
...
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;
}


This code is from NR in C. The thing is I didn't understand the line "return v-nl+NR_END;". As far as I know malloc returns the pointer to the storage allocated. Why do we have to move the pointer position back by subtracting nl+NR_END. Can anyone explain me about this. Thanks.

Bill Press
04-05-2003, 06:11 PM
Actually, the pointer is moved *forward* by NR_END. In the case of a unit offset vector (whose lowest index is 1), the NR_END and the nl cancel, so that the pointer v is returned. This is explained at the bottom of page 940 and the top of page 941 in the Numerical Recipes in C book, and has to do with the implementation of unit-offset vectors.

If you prefer (as many do) zero-offset vectors, then you should be using Numerical Recipes in C++, which has all zero-offset vectors and thus doesn't need to use this particular kludge behind the scenes.

Cheers,
Bill P.