Newsgroups: comp.lang.c Path: utzoo!utgpu!watserv1!watmath!tolstoy.waterloo.edu!mhcoffin From: mhcoffin@tolstoy.waterloo.edu (Michael Coffin) Subject: Re: Novice C question Message-ID: <1991Apr16.151220.13549@watmath.waterloo.edu> Sender: news@watmath.waterloo.edu (News Owner) Organization: University of Waterloo References: <31969@usc> Date: Tue, 16 Apr 1991 15:12:20 GMT Lines: 37 In article <31969@usc> ajayshah@almaak.usc.edu (Ajay Shah) writes: >Consider this fragment of C code (from Numerical Recipes): > >1 double *dvector(nl,nh) >2 int nl,nh; >3 { >4 double *v; >5 >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. If you want to allocate an array going from 5 to 10, >you would say p = dvector(5, 10). > >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 return a pointer to a phantom array location nl spaces to the "left" of the leftmost space actually allocated, so that after calling, for example, d = dvector(2,4) d[2],d[3], and d[4] would be within the space actually allocated. Although this will work with many C compilers, the ANSI standard does not give its blessing. A compiler is entitled to produce code that issues an error message or dumps core when it evaluates the expression "v-nl" for positive nl. Michael Coffin mhcoffin@watmsg.waterloo.edu Dept. of Computer Science office: (519) 885-1211 University of Waterloo home: (519) 725-5516 Waterloo, Ontario, Canada N2L 3G1