Simple ptr passing question
Will Crowder
willcr at bud.sos.ivy.isc.com
Tue May 14 16:01:22 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:
In the words of Agent 86, "Missed it by *that* much!"
|> #include <stdio.h>
|> main()
|> {
|> extern void zip();
|> int *ip;
|>
|> zip(ip);
should be
zip(&ip);
|> printf("*ip is %d\n",*ip);
|> }
|>
|> void zip (iptr)
|> int *iptr;
should be
int **iptr;
|> {
|> int * jptr;
|> jptr = (int *) malloc(sizeof (int) );
|> *jptr = 12;
|> iptr = jptr;
should be
*iptr = jptr;
|> }
You need to pass the address of the object you want to modify to zip().
Since you're passing the address of an int pointer, the function zip()
should expect a "pointer to a pointer to an int". Remember, in C, *everything*
is passed by value, even pointers. Your code as it stood assumed that iptr
was being passed by reference. So you missed it by three measly characters.
Other than that, the code is basically correct.
Will
--------------------------------------------------------------------------------
Will Crowder, MTS | "I was gratified to be able to answer quickly,
(willcr at ivy.isc.com) | and I did: I said I didn't know."
INTERACTIVE Systems Corp. | -- Mark Twain
More information about the Comp.lang.c
mailing list