Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!sdd.hp.com!spool.mu.edu!munnari.oz.au!uhccux!uhhacb!morrison From: morrison@uhhacb.tmc.edu (Jay Morrison) Newsgroups: comp.lang.c Subject: Re: Simple ptr passing question Message-ID: <13012@uhccux.uhcc.Hawaii.Edu> Date: 14 May 91 17:31:46 GMT Article-I.D.: uhccux.13012 References: <24268@unix.SRI.COM> Sender: news@uhccux.uhcc.Hawaii.Edu Organization: UHH Computer Science Department Lines: 59 In article <24268@unix.SRI.COM> ric@ace.sri.com (Richard Steinberger) writes: > > I am a bit rusty with C. Could someone help me with this simple >pointer passing problem. I wanted to pass a ptr to a function and >have the function allocate some space and pass back the address in the ptr. >Here's what I tried: > [etc...] > You have to pass a pointer to a pointer in this situation. I had the same problem in a lab for an operating systems class. Programming queue operations in C you need pointers to pointers also. Try this: #include main() { extern void zip(); int *ip; zip(&ip); printf("**ip is %d\n",*ip); } void zip (iptr) int **iptr; { int * jptr; jptr = (int *) malloc(sizeof (int) ); *jptr = 12; *iptr = jptr; } The problem is that in C you always pass by reference, even when you pass a pointer. In other words, it is going pass a copy of the pointer, and you are changing that copy. Upon return to your main function, the value it had there is restored. So you need to pass a pointer to the pointer, so that when you change the pointer (via *iptr = jptr), the value will be there upon return to main. Totally confused? Think about it for a while, its totally logical actually. Another common problem you may encounter is a returning a FILE* structure from a routine which opens a file. In this situation you must also use pointers to pointers. This even had my professor confused as to what was happening!! (temporarily). ---------------------------------------------------------------------- / Jay Morrison \ "C programming: all the power \ morrison@uhhacb.uhh.hawaii.edu / of assembly language with the /=================================== ease of assembly language..." \ *********** and God said: "Let there be SURF!!" *************** ----------------------------------------------------------------------