Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sdd.hp.com!uakari.primate.wisc.edu!zaphod.mps.ohio-state.edu!wuarchive!psuvax1!rutgers!cmcl2!adm!smoke!gwyn From: gwyn@smoke.brl.mil (Doug Gwyn) Newsgroups: comp.lang.c Subject: Re: Novice C question Message-ID: <15862@smoke.brl.mil> Date: 16 Apr 91 20:04:35 GMT References: <31969@usc> Organization: U.S. Army Ballistic Research Laboratory, APG, MD. Lines: 40 In article <31969@usc> ajayshah@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.