Newsgroups: comp.lang.c
Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!batcomputer!cornell!rochester!kodak!ispd-newsserver!ism.isc.com!bud.sos.ivy.isc.com!willcr
From: willcr@bud.sos.ivy.isc.com (Will Crowder)
Subject: Re: Simple ptr passing question
Message-ID: <1991May14.060122.5132@ism.isc.com>
Followup-To: comp.lang.c
Sender: usenet@ism.isc.com (Ism Usenet News)
Reply-To: willcr@ivy.isc.com
Organization: Interactive Systems Corp.
References:  <24268@unix.SRI.COM>
Date: Tue, 14 May 1991 06:01:22 GMT

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:

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@ivy.isc.com)         |  and I did: I said I didn't know."
INTERACTIVE Systems Corp.    |		-- Mark Twain
