Coder's Guild Mailing List

Re: Re: C Question

Posted by DaRKFoRCe on 2000-03-12

Hi,

Saturday, March 11, 2000, 4:10:41 AM, you wrote:

tgoa> Date: Thu, 9 Mar 2000 15:41:46 -0800 (PST)
tgoa> From: Kwisatz Haderach <snrrrub@xxxxx.xxx>
tgoa> Subject: Re: C Question

>snipped...

tgoa> Yes, I know I COULD do that, but that's not what I was
tgoa> asking! :( I need to know if there's a way to pass a
tgoa> pointer by reference (without using global variables,
tgoa> without returning a pointer, etc.)! Let me try another
tgoa> example:

>snipped...

Let me get this straight, you want to modify the content of a pointer
by passing that pointer to a function? If that is true, then look at
the sample code below, it it's not, then ignore this post.

/* Allocate a heightfield with dimension row X col */
int allocField(unsigned int ***f, int row, int col)
{
 int x, y;
 unsigned int **tmp;

 if((tmp=(unsigned int **)malloc(col*sizeof(unsigned int *))) == NULL)
 {
  return(-1);
 }

 for(x=0;x<col;x++)
 {
  if((tmp[x]=(unsigned int *)malloc(row*sizeof(unsigned int))) == NULL)
  {
   freeField(tmp,x);
   return(-1);
  }
 }

 for(y=0;y<row;y++)
 {
  for(x=0;x<col;x++)
     tmp[x][y] = 65535;
 }
 *f = tmp;
 return(0);
}

/* invocation */
int main(int argc, char argv[])
{
 unsigned int **hfield;
 ...
 ...
 if(allocField(&hfield,row,col))
 {
  printf("could not allocate height field");
  return(0);
 }
 ...
 return 0;
}

The code is taken from earlier implementation of a project of mine.
The function allocField() is allocating a 2D array for a given row and
col. After the array is allocated, the address of the array is given
to a pointer that was passed to the function.

The code is compiled fine with DJGPP.

Hope this helps.

DaRKFoRCe
darkforce@xxxxxxxxxxx.xxx


To signoff send a mail to listserver@xxxx.xx.xx with 
  "signoff tcg" in the body of your message.