Simple ptr passing question
Jay Morrison
morrison at uhhacb.tmc.edu
Wed May 15 03:31:46 AEST 1991
In article <24268 at unix.SRI.COM> ric at 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 <stdio.h>
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 at uhhacb.uhh.hawaii.edu / of assembly language with the
/=================================== ease of assembly language..."
\ *********** and God said: "Let there be SURF!!" ***************
----------------------------------------------------------------------
More information about the Comp.lang.c
mailing list