Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!mcsun!hp4nl!dri500!heinhuis From: heinhuis@dri.nl (Gustaaf-Jan Heinhuis) Newsgroups: comp.lang.c Subject: Re: Novice C question Message-ID: <992@dri500.dri.nl> Date: 16 Apr 91 08:52:52 GMT References: <31969@usc> Organization: DataCount Register Informatici, Wierden, The Netherlands Lines: 46 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? > >Thanks! > Well, I know why he substracts nl. The fact that you have an array from 5 to 10 implies you also have indexes 0 to 4. The lowest index your going to use is 5 which is an offset to a base adress. To make this work the base adress has to 5 units (= nl, unit depends on type of reserved memory; here it's double) lower as the adress of the allocated block of memory. You can, however, not use p[0] to p[4] because you didn't alloc any memory for this part of the array. Hope this answers your question, Gustaaf-Jan. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++---===To all virgins, thanks for nothing.===---++++++++++++++ ___ GJ Heinhuis student comp. sc. HIO Enschede (Holland) / _) Final Project at: DataCount, Wierden, Holland | ____ ___ Mail: heinhuis@dri.nl \__/| | |___| Everybody is entitled to his own | | | opinion, as long as it's mine! \_/ | Not necessarely DataCount's opinion!!