Novice C question
Doug Gwyn
gwyn at smoke.brl.mil
Wed Apr 17 06:04:35 AEST 1991
In article <31969 at usc> ajayshah at almaak.usc.edu (Ajay Shah) writes:
>Consider this fragment of C code (from Numerical Recipes):
Ugh, but okay.
>1 double *dvector(nl,nh)
>2 int nl,nh;
>3 {
>4 double *v;
>6 v=(double *)malloc((unsigned) (nh-nl+1)*sizeof(double));
>7 if (!v) nrerror("allocation failure in dvector()");
>8 return v-nl;
>9 }
>It's supposed to be a function which allocates a vector of doubles.
>My interpretation of nl and nh is: they're array indexes.
They're supposed to be the minimum and maximum indices that will be
used to access the vector after it is allocated.
>Question: what is happening on line 8? Why is he not just
>returning v (a pointer)? What is the meaning of subtracting nl
>(an int) from v without any casting?
The intention is to be able to use dvector() like this:
double *v = dvector(5,10);
v[5] = 42.0;
/* ... */
v[10] = 3.1416;
The returned pointer is supposed to be offset so that v[5] will
access the first location in the object allocated by malloc().
Pointer_to_thing plus or minus some integer is an expression that
has type pointer_to_thing and a value that points to that integer
number of "things" away from the original pointer.
Unfortunately, v-nl does not necessarily point to anything valid
(who knows what lurks below the address returned by malloc()?),
so this function may fail (most likely catastrophically) on many
C implementations.
The Numerical Recipes C code is terrible; this is just one example.
More information about the Comp.lang.c
mailing list